2012-08-16 67 views
0

我有一個通用字典集合字典。我需要將DisplayMember路徑關鍵複選框和複選框器isChecked財產的內容結合到詞典如何將字典對象綁定到checkedlistbox使用WPF

private Dictionary<string, bool> _columnHeaderList; 
    public Dictionary<string, bool> ColumnHeaderList 
    { 
     get { return _columnHeaderList; } 
     set { _columnHeaderList = value; RaisePropertyChanged("ColumnHeaderList"); } 
    } 

    private Dictionary<string, bool> GetColumnList() 
    { 
     Dictionary<string, bool> dictColumns = new Dictionary<string, bool>(); 
     Array columns = Enum.GetValues(typeof(ColumnHeaders)); 
     int arrayIndex=0; 
     for(int i=0;i<columns.Length;i++) 
     { 
      dictColumns.Add(columns.GetValue(arrayIndex).ToString(), true); 
     } 
     return dictColumns; 

    } 

我的XAML值的成員看起來像

<ListBox Grid.Column="0" Grid.Row="1" Height="200" 
      ItemsSource="{Binding ColumnHeaderList}" 
      VerticalAlignment="Top"> 
     <ListBox.ItemTemplate> 
      <HierarchicalDataTemplate> 
       <CheckBox Content="{Binding key}" IsChecked="{Binding Path=Value}"></CheckBox> 
      </HierarchicalDataTemplate>    
     </ListBox.ItemTemplate>   
    </ListBox> 

回答

0

呀它的可能性,它也應該工作,儘管你需要綁定值綁定模式爲OneWay,因爲字典值不能設置,因爲它的readOnly。如果你想改變這個值,你可以掛上Command(if following MVVVM)或者可以在Checked event後面的代碼中處理。

此外,還有對Key的綁定不正確,請將您的key替換爲Key。你最終的XAML應該是這樣的 -

<ListBox Grid.Column="0" Grid.Row="1" Height="200" 
      ItemsSource="{Binding ColumnHeaderList}" 
      VerticalAlignment="Top"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <CheckBox Content="{Binding Key}" 
        IsChecked="{Binding Path=Value, Mode=OneWay}"/> 
     </DataTemplate>    
    </ListBox.ItemTemplate>   
</ListBox> 

注意我有DataTemplate改變了HierarchicalDataTemplate,因爲我看不到模板中的所有層次。

1

如果綁定到Dictionary,您將需要使用OneWay綁定,因爲KeyValuePair具有隻讀屬性。

<CheckBox Content="{Binding Key, Mode=OneWay}" IsChecked="{Binding Path=Value, Mode=OneWay}" Width="100" /></CheckBox> 

確保您已設置DataContext。請注意,當用戶按下複選框時,這不會更新字典值。

0

由於Value屬性是隻讀的,並且OneWay綁定不會允許您跟蹤更改,如果用戶選中或取消選中複選框。建議將它們與陣列新類ListItem綁定:

class ListItem 
{ 
    public string Text { get; set; } 
    public bool IsChecked { get; set; } 
} 

private ListItem[] GetColumnList() 
{ 
    return Enum.GetValues(typeof(ColumnHeaders)) 
       .Select(h => new ListItem{ Text = h.ToString(),IsChecked = true}) 
       .ToArray(); 

}