我有一个问题,我在 WPF 中有一个如下所示的组合框:
<ComboBox IsSynchronizedWithCurrentItem="True"
commands:PropertyChangeBehavior.Command="{Binding GetCurrentsModuleCommand}"
SelectedItem="{Binding SelectedModule, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
<ComboBox.ItemsSource>
<CompositeCollection>
<ComboBoxItem IsEnabled="True" Content="All">
<ComboBoxItem.Tag>
<system:Int32>0</system:Int32>
</ComboBoxItem.Tag>
</ComboBoxItem>
<CollectionContainer Collection="{Binding Source={StaticResource ResourceKey=ModulesCombo}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>
现在 source 只是一个整数列表,但我需要一些默认值,所以我添加了 ComboBoxItem
。现在选定的项目属性如下所示:
private int selectedModule;
public int SelectedAModule
{
get => selectedModule;
set
{
selectedModule = value;
OnPropertyChanged();
}
}
当更改为默认值时,我得到了
System.Windows.Data Error: 23 : Cannot convert 'System.Windows.Controls.ComboBoxItem: All' from type 'ComboBoxItem' to type 'System.Int32'
如果我检查命令:
public ICommand GetCurrentsModuleCommand => new Command(module =>
{
SomeLogic();
});
如果它是一个正常值模块是一个数字,但如果它是我得到的所有值:
"System.Windows.Controls.ComboBoxItem: All";
有什么办法可以解决这个问题吗?
最佳答案
另一种解决方案是绑定(bind)到 Dictionary,其中 Key 选择 int,value 是 ComboBox 项目的标签:
public Dictionary<int, string> dic { get; set; } = new Dictionary<int, string>()
{
[0] = "All",
[1] = "1",
[2] = "2"
};
具有选定值的属性:
public int SelectedValue { get; set; }
接下来,您可以像这样创建 ComboBox:
<ComboBox
DisplayMemberPath="Value"
ItemsSource="{Binding dic}"
SelectedValue="{Binding SelectedValue}"
SelectedValuePath="Key" />
DisplayMemberPath 是字典中的值,它将显示在 ComboBox 中,SelectedValue 是要存储所选索引的 int 属性,SelectedValuePath 是字典中的键(在 ComboBox 中选择某些内容后,它将存储在 SelectedValue 中)
关于c# - WPF从复选框转换选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49512602/