Как программно обновить источник элементов в автоматически сгенерированной ячейке списка данных
Я не могу найти рабочее решение моей проблемы
У меня есть сетка данных, связанная с коллекцией объектов. одно из моих свойств объекта используется в качестве индекса в коллекции. В автоматически создаваемом столбце комбинированного списка "Тип" отображается "метка", связанная с этим индексом.
Мне нужно обновить другое свойство, которое тоже является индексом в том же объекте. Я использую этот код для добавления комбинированного списка в событие AutogeneratingColumn:
public partial class LedTableEditor : MetroWindow, INotifyPropertyChanged
{
private object _sender;
public Dictionary<int, string> IdColors = new Dictionary<int, string>();
public ObservableCollection<Xceed.Wpf.Toolkit.ColorItem> MarshallingColors = new ObservableCollection<Xceed.Wpf.Toolkit.ColorItem>();
private Dictionary<int, string> cbTypeVals = new Dictionary<int, string>();
private Dictionary<UInt16, string> cbSrcValueVals = new Dictionary<UInt16, string>();
private Dictionary<UInt16, string> cbDiagVals = new Dictionary<UInt16, string>();
private List<string> ListeData = new List<string>();
private List<string> ListeDiag = new List<string>();
private int maxLeds = 16;
private XapLedVals led;
public LedTableEditor(object senderParam)
{
-----
}
private void DgLedTable_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "Type")
{
DataGridComboBoxColumn cbType = new DataGridComboBoxColumn();
cbType.EditingElementStyle = new Style(typeof(ComboBox))
{
Setters =
{
new EventSetter(Selector.SelectionChangedEvent, new SelectionChangedEventHandler(OnComboBoxSelectionChanged))
}
};
e.Column = cbType;
cbType.ItemsSource = cbTypeVals; // new List<string> { eLedType.ALERTE.ToString(), eLedType.DIAG.ToString(), eLedType.TRIGGER.ToString() };
cbType.DisplayMemberPath = "Value";
cbType.SelectedValuePath = "Key";
cbType.SelectedValueBinding = new Binding("Type");
e.Column.Header = "Type";
e.Column.CellStyle = new Style(typeof(DataGridCell));
e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.HorizontalAlignmentProperty, HorizontalAlignment.Stretch));
}
if (e.PropertyName == "Binding")
{
DataGridComboBoxColumn cbBinding = new DataGridComboBoxColumn();
BindingOperations.SetBinding(cbBinding, DataGridComboBoxColumn.ItemsSourceProperty, new Binding("Source") { Source = this });
e.Column = cbBinding;
cbBinding.ItemsSource = cbSrcValueVals;
cbBinding.DisplayMemberPath = "Value";
cbBinding.SelectedValuePath = "Key";
cbBinding.SelectedValueBinding = new Binding("Binding");
e.Column.Header = "Binding";
e.Column.CellStyle = new Style(typeof(DataGridCell));
e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.HorizontalAlignmentProperty, HorizontalAlignment.Stretch));
}
----
}
Исходный текст в выпадающем списке "Тип" представляет собой словарь:
private Dictionary<int, string> cbTypeVals = new Dictionary<int, string>();
Мне нужно обновить этот источник элемента списка "Связывание", который тоже генерируется автоматически в той же самой сетке данных:
if (e.PropertyName == "Binding")
{
AutoCommitComboBoxColumn cb = new AutoCommitComboBoxColumn();
e.Column = cb;
cb.ItemsSource = cbSrcValueVals;
cb.DisplayMemberPath = "Value";
cb.SelectedValuePath = "Key";
cb.SelectedValueBinding = new Binding("Binding");
e.Column.Header = "Binding";
e.Column.CellStyle = new Style(typeof(DataGridCell));
e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.HorizontalAlignmentProperty, HorizontalAlignment.Stretch));
}
Источник элемента комбинированного списка "Связывание" представляет собой словарь:
private Dictionary<UInt16, string> cbSrcValueVals = new Dictionary<UInt16, string>();
это должно быть обновлено с этим:
private Dictionary<UInt16, string> cbDiagVals = new Dictionary<UInt16, string>();
Событие запущено правильно, но я не могу найти способ обновить элементы списка "Связывание".
private void OnComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
{
DgLedTable.CurrentCell = new DataGridCellInfo(DgLedTable.SelectedIndex, DgLedTable.Columns[1]);
}
Спасибо за помощь.
Отредактируйте здесь изображение экрана с элементами в ComboBox "Тип":
Изменить, добавлен код для свойства:
private System.Collections.IEnumerable _source;
public System.Collections.IEnumerable Source
{
get { return _source; }
set { _source = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void OnComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
{
// DgLedTable.CurrentCell = new DataGridCellInfo(DgLedTable.SelectedIndex, DgLedTable.Columns[1]);
Source = cbDiagVals;
}
1 ответ
Если вы создаете исходное свойство и связываете ItemsSource
собственность "Binding" ComboBox
к этому вы можете установить это свойство для новой коллекции в "Тип" ComboBox's
SelectionChanged
обработчик события.
Окно - или в любом другом типе вашего кода - должно реализовывать интерфейс INotifyPropertyChanged, чтобы это работало:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private Dictionary<int, string> cbTypeVals = new Dictionary<int, string>();
private Dictionary<UInt16, string> cbSrcValueVals = new Dictionary<UInt16, string>();
private Dictionary<UInt16, string> cbDiagVals = new Dictionary<UInt16, string>();
public MainWindow()
{
InitializeComponent();
_source = cbTypeVals;
//...
}
private System.Collections.IEnumerable _source;
public System.Collections.IEnumerable Source
{
get { return _source; }
set { _source = value; OnPropertyChanged(); }
}
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "Binding")
{
AutoCommitComboBoxColumn cb = new AutoCommitComboBoxColumn();
e.Column = cb;
//bind the ItemsSource property to the Source property of the window here...
cb.SetBinding(AutoCommitComboBoxColumn.ItemsSourceProperty, new Binding("Source") { Source = this });
cb.ItemsSource = cbSrcValueVals;
cb.DisplayMemberPath = "Value";
cb.SelectedValuePath = "Key";
cb.SelectedValueBinding = new Binding("Binding");
e.Column.Header = "Binding";
e.Column.CellStyle = new Style(typeof(DataGridCell));
e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.HorizontalAlignmentProperty, HorizontalAlignment.Stretch));
}
//...
}
private void OnComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
{
//set the value of the Source property to a new collection and raise the PropertyChanged event here...
Source = cbDiagVals;
}
public event PropertyChangedEventHandler PropertyChanged;
private virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
//...
}