c# - WPF从复选框转换选定值

标签 c# wpf

我有一个问题,我在 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/

相关文章:

c# - HashSet 到 List 的转换

c# - TcpListener 常量错误 每个地址只使用一次

c# - WCF Silverlight HTTP 和 HTTPS

C# WMI 进程差异化?

wpf - 如何将样式触发器应用于 WPF 中的数据模板

c# - 当 Pen 具有 Null 以外的 DashStyle 时,StreamGeometry 不会被栅格化

WPF MVVM - 存储库模式查询

.net - C# WPF 项目无法调用 F# 库

wpf - 解释 Visual Studio 2010 及更高版本、WinForms 和 WPF 中的关键错误

c# - 如何减小 Crystal 报表工具栏的宽度?