Чтобы сделать это программно, вот общая функция у меня есть:
/// <summary>
/// Thread safe method for databinding the specified ComboBox with the specified data.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ctrl">The Combo to be databound.</param>
/// <param name="datasource">The data to be bound to the Combo.</param>
/// <param name="displayPath">The name of the property in the data objects that should be used for the display value.</param>
/// <param name="valuePath">The name of the property in the data objects that should be used for the value.</param>
/// <remarks>
/// This function was written as generic so that it doesn't matter what types the IEnumerabe datasource is, it can handle them all.
/// </remarks>
private void UpdateComboDataSource<T>(ComboBox ctrl, IEnumerable<T> datasource, string displayPath, string valuePath)
{
if (ctrl == null)
throw new ArgumentNullException("Control to be bound must not be null");
//check if we are on the control's UI thread:
if (ctrl.Dispatcher.CheckAccess())
{
//we have full access to the control, no threading issues, so let's rip it up and databind it
datasource = datasource.OrderBy(x => x);
if (displayPath != null && ctrl.DisplayMemberPath == null)
ctrl.DisplayMemberPath = displayPath;
if (valuePath != null && ctrl.SelectedValuePath == null)
ctrl.SelectedValuePath = valuePath;
ctrl.ItemsSource = datasource;
//be nice to the user, if there is only one item then automatically select it
ctrl.SelectedIndex = datasource.Count() == 1 ? 0 : -1;
}
else
{
//we don't have full access to the control because we are running on a different thread, so
//we need to marshal a call to this function from the control's UI thread
UpdateComboDataSourceDelegate<T> del = new UpdateComboDataSourceDelegate<T>(this.UpdateComboDataSource);
ctrl.Dispatcher.BeginInvoke(del, ctrl, datasource, displayPath, valuePath);
}
}
private delegate void UpdateComboDataSourceDelegate<T>(ComboBox ctrl, IEnumerable<T> dataSource, string displayPath, string valuePath);
Комментарии сообщают вам все, что вам нужно знать. Это также можно было бы сделать программно, создав Binding
между объектом управления ItemSource
и общедоступной собственностью на вашей странице - это так же, как это сделано декларативно (там должно быть миллиард примеров этого, хотя я и выиграл ' t показать его здесь).
После прочтения ваш пост снова, вы имеете в виду, что набор данных будет привязан к DataGrid, и комбо будет занимать каждую ячейку в столбце этого DataGrid? Или вы имеете в виду, что комбо просто сидит в гриде? (Существует большая разница между ними). Мой ответ ниже, когда комбо является частью обычного потока для страницы, то есть находится в гриде. – slugster
Комбо только сидит в гриде, и мне нужно загрузить некоторые значения :-) – Vytas