如何使用WPF将Dictionary对象绑定到checkedlistbox
我有一本通用字典集。我需要将displaymember路径键绑定到checkbox的内容,将checkbox Ischecked属性绑定到字典的value成员如何使用WPF将Dictionary对象绑定到checkedlistbox,wpf,checkedlistbox,Wpf,Checkedlistbox,我有一本通用字典集。我需要将displaymember路径键绑定到checkbox的内容,将checkbox Ischecked属性绑定到字典的value成员 private Dictionary\u专栏作家; 公共词典专栏作家 { 获取{return\u columnerList;} 设置{u columnHeaderList=value;RaisePropertyChanged(“columnHeaderList”);} } 私有字典GetColumnList() { Dictionary
private Dictionary\u专栏作家;
公共词典专栏作家
{
获取{return\u columnerList;}
设置{u columnHeaderList=value;RaisePropertyChanged(“columnHeaderList”);}
}
私有字典GetColumnList()
{
Dictionary dictColumns=新字典();
Array columns=Enum.GetValues(typeof(columnheader));
int-arrayIndex=0;
对于(int i=0;i是的,这是可能的,它也应该可以工作,尽管您需要使用绑定模式为单向的值进行绑定,因为字典值是只读的,无法设置。如果您希望更改值,可以挂接命令(如果遵循MVVVM)
,或者可以在Checked事件上处理代码隐藏
另外,键
的绑定也不正确,请将键
替换为键
。最终的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
更改了hierarchycaldatatemplate
,因为我在模板中看不到任何层次结构。如果绑定到字典,则需要使用单向绑定,因为KeyValuePair具有只读属性
<CheckBox Content="{Binding Key, Mode=OneWay}" IsChecked="{Binding Path=Value, Mode=OneWay}" Width="100" /></CheckBox>
确保已设置DataContext。注意,当用户按下复选框时,这不会更新字典值。因为Value属性是只读的,如果用户选中或取消选中复选框,单向绑定将不允许您跟踪更改。建议使用数组新类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();
}
您能添加编译所需的代码吗?(RaisePropertyChanged和ColumnHeader)?
<CheckBox Content="{Binding Key, Mode=OneWay}" IsChecked="{Binding Path=Value, Mode=OneWay}" Width="100" /></CheckBox>
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();
}