2016-07-25 8 views
0

Dictionary<string, string>ComboBoxがあるとします。ここでアイテムはその辞書のキーを保持するコレクションから取り込まれます。 TextBlockを選択したキーの値にバインドするにはどうすればよいですか?バインディングでキーが与えられている辞書エントリにTextBlockをバインドする方法は?

<ComboBox ItemsSource="{Binding MyKeyCollection}"/> 

<TextBox Text={Binding //What do I put here? }/> 

答えて

0

ここでは、コンボボックス内のデータをバインドする方法です -

<ComboBox ItemsSource="{Binding SomeCollection}"> 

     <ComboBox.ItemTemplate> 

      <DataTemplate> 

       <StackPanel Orientation="Horizontal"> 

        <TextBlock Text="{Binding Key}" 
           Margin="5"/> 
        <TextBlock Text="{Binding Value}" 
           Margin="5"/> 

       </StackPanel>         

      </DataTemplate> 

     </ComboBox.ItemTemplate> 

    </ComboBox> 

スタイル、それはあなたが望むものを達成するためにDataTemplateを

0

に望むように、あなたは必ず、あなたのことをする必要がViewModel KeyCollectionと辞書の両方を保持します。ここに私の解釈:

は、あなたがこのビューモデルがあるとします。

public class DictVm 
    { 
     public Dictionary<string, string> MainDictionary { get; set; } 
     public ObservableCollection<string> MyKeyCollection{ get; set; } 
     public string SelectedKey{ get; set; } 

     private string _selectedDictValue; 
     public string SelectedDictValue { 
     get { 

      if (MainDictionary.TryGetValue(SelectedKey, _selectedDictValue)) 
       return _selectedDictValue; 
      return string.Empty; 
     } 
     set { _selectedDictValue = value; } } 
    } 

ここでは、あなたのメイン・ウィンドウコンストラクタは次のとおりです。

private DictVm vm; 
    public MainWindow() 
    { 
     InitializeComponent(); 

     vm = new DictVm(); 
     DataContext = vm; 
    } 
私はXAMLを変更する方法をここで

<ComboBox x:Name="MyCombo" ItemsSource="{Binding MyKeyCollection}" SelectedValue="{Binding SelectedKey}"/> 

<TextBox Text="{Binding SelectedDictValue}"/> 
関連する問題