2017-02-10 15 views
0
поля со списком

я не могу найти рабочее решение моей проблемуКак обновить программно источник элементов в пределах автогенерируемого DataGrid ячейки

У меня есть DataGrid переплетены к коллекции объектов. одно из свойств моего объекта используется как индекс в коллекции. Автогенерированный столбец combobox «Тип» отображает «метку», связанную с этим индексом.

Мне нужно обновить другое свойство, которое также является индексом в том же самом объекте. Я использую этот код, чтобы добавить выпадающие в случае 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>(); 

мне нужно обновить этот «Binding» источник выпадающего пункта, который автоматически сгенерирован тоже в той же сетке:

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>(); 

Событие правильно уволили, но я не могу найти способ, чтобы обновить «Binding» пунктов ComboBox.

private void OnComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    DgLedTable.CurrentCell = new DataGridCellInfo(DgLedTable.SelectedIndex, DgLedTable.Columns[1]); 
} 

Благодарим за помощь.

Редактировать здесь изображение экрана с пунктами в ComboBox «Тип»:

enter image description here

Редактировать, код добавлен для недвижимости изменился:

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; 
    } 
+0

Так что вы хотите изменить ItemsSource в «Binding» ComboBox от «cbSrcValueVals» в какая-то другая коллекция, не так ли? Какую коллекцию вы хотите использовать в качестве нового элемента ItemsSource? – mm8

+0

да точно, если тип combo box установлен в 2, мне нужно обновить «Binding» combobox с другим словарем: 'private Dictionary cbDiagVals = new Dictionary ();' – Alexus

ответ

1

При создании свойства источника and bind ItemsSource property "Binding" ComboBox к этому объекту, вы можете было установить это свойство на новую коллекцию в руководстве «Тип» ComboBox'sSelectionChanged.

окно - или в любой тип код определен - должен реализовывать интерфейс 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)); 
    } 

    //... 
} 
+1

OK, I забыл удалить строку 'cbBinding.ItemsSource = cbSrcValueVals;' code ... она была сброшена каждый раз. Спасибо за вашу помощь и элегантное решение ... и терпение! – Alexus

+0

У меня есть еще один вопрос: как я могу установить источник комбо-привязки при повторном открытии окна. По умолчанию «Binding» ComboBox устанавливается с первым dictionnary cbSrcValueVals. – Alexus

+1

Удаление дополнительных комментариев здесь. @Alexus. Если у вас есть другой вопрос, пожалуйста, спросите его, нажав кнопку [Ask Question] (// stackoverflow.com/questions/ask) вместе с [mcve].Вы можете ссылаться на этот вопрос в своем новом вопросе, но попробуйте проверить связанные сообщения, прежде чем публиковать их. –