2016-03-30 3 views
0

У меня есть три ComboBox. Threre связаны с тем же ItemsSource.Как я могу связать множество элементов ComboBoxСвязь друг с другом

Этот тип ItemsSouce является Dictionary<string, Dictionary<CustomKey, CustomClass>>

CustomKey

public struct CustomKey<T1,T2> // T1, T2 is string 
{ 
    public readonly T1 Symbol; 
    public readonly T2 Column; 
    public CustomKey(T1 key1, T2 key2) { Symbol = key1; Column = key2; } 
} 

CustomClass

public class CustomClass 
{ 
    public string Value{get;set} 
} 

Во-первых. ItemsSoure FirstComboBox является Dictionary.Keys

Второй. Я хочу установить элементы Second ComboBox Source - это SelectedItems FirstComboBox.
как это словарь [FirstComboBox.SelectedItem] .Keys T1

В-третьих. ThirdComboBox в ItemsSource словарь [FirstComboBox.SelectedItem] .Keys T2

Последний.
Это мой код ...
// Source.GetNames is ItemsSource.Keys.ToList();

protected virtual FrameworkElement CreateAutoCompleteComboBoxControl(PropertyItem property) 
    { 
     var c = new AutoCompleteComboBox(); 
     ContinuityBindablePropertyItem cbp = (property as ContinuityBindablePropertyItem); // cbp is First ComboBox SelectedItem Descriptor. but i don't know how to use... 

     if (property.DisplayName == "Sheet") // First ComboBox 
     { 
      c.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("Source.GetSheetNames"); 
     } 
     else if (property.DisplayName == "TestName") // Second ComboBox 
     { 
      c.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("Source.GetSheetNames"); 
     } 
     else if (property.DisplayName == "Symbol") // Third ComboBox 
     { 
      c.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("Source.GetSheetNames"); 
     } 

     c.SetBinding(ComboBox.TextProperty, property.CreateBinding()); 
     return c; 
    } 

Просьба помочь мне. Я плохо говорю по-английски. Надеюсь, вы понимаете.

спасибо.


РЕДАКТИРОВАТЬ метод изменения.

protected virtual FrameworkElement CreateAutoCompleteComboBoxControl(PropertyItem property) 
    { 
     StackPanel s = new StackPanel(); 
     var c1 = new AutoCompleteComboBox { Name = "c1", DisplayMemberPath = "Key", IsEditable = property.IsEditable, ItemsSource = property.ItemsSource, VerticalContentAlignment = VerticalAlignment.Center }; 
     var c2 = new AutoCompleteComboBox { IsEditable = property.IsEditable, ItemsSource = property.ItemsSource, VerticalContentAlignment = VerticalAlignment.Center }; 
     var c3 = new AutoCompleteComboBox { IsEditable = property.IsEditable, ItemsSource = property.ItemsSource, VerticalContentAlignment = VerticalAlignment.Center }; 

     c1.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("Source") { Source = MappingService.Instance, Mode = BindingMode.OneWay }); 
     c2.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("Values") { Source = c1.SelectedItem, Mode = BindingMode.OneWay }); 
     c3.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("SelectedItem.Values") { ElementName = c1.Name, Mode = BindingMode.OneWay }); 

     c1.SetBinding(ComboBox.TextProperty, property.CreateBinding()); 
     c2.SetBinding(ComboBox.TextProperty, property.CreateBinding()); 
     c3.SetBinding(ComboBox.TextProperty, property.CreateBinding()); 

     s.Children.Add(c1); 
     s.Children.Add(c2); 
     s.Children.Add(c3); 
     return s; 
    } 

я пытаюсь привязки пути 'значения', 'Value', 'SelectedItem.Value', «SelectedItem.Values, Изменить источник для C1.SelectedItem или элемента имя = c1 ...

но это не работает

Редактировать
Добавление изображения. enter image description here

+0

У вас есть xaml, или вы все делаете в коде? – Joe

+0

@joe да я не ues xaml. только код за – user3214694

+0

Что такое itemSource вашего первого combobox. Можете ли вы добавить полную структуру? это не очень понятно. Я хочу установить Second ComboBox. Items Source - это SelectedItems FirstComboBox. как этот словарь [FirstComboBox.SelectedItem] .Keys T1 В-третьих. ThirdComboBox's ItemsSource Dictionary [FirstComboBox.SelectedItem] .Keys T2 – Nitin

ответ

1

Я немного смущен именно тем, что вы пытаетесь сделать, я думаю, мне понадобится немного больше кода или пример, чтобы окунуться в него. Но я попробую обратиться к некоторым вопросам. Кроме того, я привык к xaml, поэтому вам может понадобиться заполнить пробелы кода привязки:

Первый. FirstComboBox's ItemsSoure - Dictionary.Keys

Просто, чтобы проверить, это работает?

Второй. Я хочу установить Second ComboBox's Items Source: SelectedComboBox's SelectedItems. например, Словарь [FirstComboBox.SelectedItem] .Keys T1

В-третьих. ThirdComboBox в ItemsSource словарь [FirstComboBox.SelectedItem] .Keys T2

Эти две, по существу, та же проблема, вы хотите связать с Dictionary.Keys, но имеют один COMBOBOX дисплей T1 и T2 другой? Хорошо, вместо того, чтобы пытаться привязать ComboBox к Dictionary [FirstComboBox.SelectedItem] .Keys T1 напрямую, я бы предложил использовать один из двух методов.

1. Используйте конвертер с несколькими связями. Ваш первый элемент checkbox's ItemsSource будет привязан к списку строк. Это SelectedItem будет строкой, которая является ключом к Словарь>.

Вы можете передать ключ и словарь к преобразователю MultiBinding и он возвращает ключи Словаря в виде списка или массив, как это:

public class MyDictionaryValueConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     //first item is our key 
     string key = values[0] as string; 

     //second item is our dictionary 
     Dictionary<string, Dictionary<CustomKey, CustomClass>> dictionary = values[1] as Dictionary<string, Dictionary<CustomKey, CustomClass>>; 

     //pass our value to be bound to 
     return dictionary[key].Keys.ToList(); 
    } 
} 

Вы знаете, как установить преобразователь привязку в коде? Возможно, вам нужно исследовать multibindings, я только когда-либо делал это в xaml.

2. Вы также можете сделать это, используя промежуточные свойства Вы не должны связываться все сразу, вы можете создать свойство в данных объекта, как это:

public class DataContextThatContainsYourDictionary : INotifyPropertyChanged 
{ 
    //notifying property that is bound to ItemsSource in the first Combobox 
    public Dictionary<string, Dictionary<CustomKey, CustomClass>> MyDictionary { get... } 

    //This is the string that's bound to SelectedItem in the first ComboBox 
    public string SelectedKey 
    { 
     get 
     { 
      return selectedKey; 
     } 
     set 
     { 
      //standard notify like all your other bound properties 
      if (selectedKey != value) 
      { 
       selectedKey = value; 
       //when this changes, our selection has changed, so update the second list's ItemsSource 
       SelectedKeys = MyDictionary[SelectedKey].Keys.ToList(); 
       NotifyPropertyChanged("SelectedKey"); 
      } 
     } 
    } 

    //an "intermediatary" Property that's bound to the second Combobox, changes with the first's selection 
    public List<CustomKey> SelectedKeys { get ... } 

Они оба имеют тот же результат, вы в конечном итоге привяжете свои ComboBoxes к списку. Затем вы можете установить DisplayMemberPath в T1 для первого флажка или T2 для второго.

+0

добавь картинку для справки мои вопросы – user3214694

+0

Да, первый comboBox работает. но второе и третье поле не работают. – user3214694

+0

и ... '@joe' << - не работает .. – user3214694

1

Попробуйте установить привязки, как показано ниже: Возможно, вам нужно будет установить DisplayMemberPath для двух других выпадающих списков в зависимости от того, какое свойство вы хотите показать в них.

var c1 = new AutoCompleteComboBox { Name = "c1", DisplayMemberPath = "Key", IsEditable = property.IsEditable, VerticalContentAlignment = VerticalAlignment.Center }; 
var c2 = new AutoCompleteComboBox { IsEditable = property.IsEditable, VerticalContentAlignment = VerticalAlignment.Center }; 
var c3 = new AutoCompleteComboBox { IsEditable = property.IsEditable, VerticalContentAlignment = VerticalAlignment.Center }; 

c1.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("Source") { Source = MappingService.Instance, Mode = BindingMode.OneWay }); 
c2.SetBinding(ItemsControl.ItemsSourceProperty, new Binding() { Path = new PropertyPath("SelectedItem.Value.Keys"), ElementName = c1.Name, Mode = BindingMode.OneWay }); 
c3.SetBinding(ItemsControl.ItemsSourceProperty, new Binding() { Path = new PropertyPath("SelectedItem.Value.Values"), ElementName = c1.Name, Mode = BindingMode.OneWay }); 

 Смежные вопросы

  • Нет связанных вопросов^_^