Multiselect Combobox w / Flags Enum

时间:2015-04-18 13:07:29

标签: c# wpf combobox enums

我希望有人可以帮我解决这个问题。我以前曾问过类似的问题,但我当时没有开始做任何事情。我找到了SO问题link

这与我的问题类似,但它有一个问题。组合框不显示所选的枚举。我在我的示例应用程序中的链接中进行了示例,但我不知道如何获取Combobox的文本以显示当前选定的项目。有人建议怎么办?我真的被困在这个。

这是我目前的组合框:

<ComboBox>
    <CheckBox Content="SAW" IsChecked="{Binding Path=CurWeldingProcess, Converter={StaticResource wpFlagValueConverter}, ConverterParameter={x:Static models:WeldingProcess.SAW}}" />
    <CheckBox Content="FCAW" IsChecked="{Binding Path=CurWeldingProcess, Converter={StaticResource wpFlagValueConverter}, ConverterParameter={x:Static models:WeldingProcess.FCAW}}" />
    <CheckBox Content="SMAW" IsChecked="{Binding Path=CurWeldingProcess, Converter={StaticResource wpFlagValueConverter}, ConverterParameter={x:Static models:WeldingProcess.SMAW}}" />
</ComboBox>

我的转换器是:

public class WeldingProcessFlagValueConverter : IValueConverter
{
    private WeldingProcess target;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        WeldingProcess mask = (WeldingProcess)parameter;
        this.target = (WeldingProcess)value;
        return ((mask & this.target) != 0);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        this.target ^= (WeldingProcess)parameter;
        return this.target;
    }
}

所以当我选择复选框的任意组合时,我的'CurWeldingProcess'显示正确的值,但我不知道如何让组合框显示所选的值('CurWeldingProcess')。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

如果你需要显示&#34; concatenation&#34;所选项目(例如,如果我检查SAW和SMAW枚举值,我希望在ComboBox文本中看到类似&#34; SAW,SMAW和#34;),你可以看看这个Multi Select ComboBox in WPF

你会发现MVVM版本和&#34;代码隐藏&#34;之一。

修改

好的,你可以去CodeProject并下载MultiSelectComboBox dll。将其添加到您的项目中。 然后在您的XAML中添加:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:multi="clr-namespace:MultiSelectComboBox;assembly=MultiSelectComboBox"
        Title="MainWindow" Height="350" Width="600">
    <!-- your xaml -->
        <multi:MultiSelectComboBox Margin="4" Name="MultiSelectComboBox" />
    <!-- the rest of your xaml -->
</Window>

然后在你的代码隐藏中(我用我的样本TextAlignment枚举):

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Dictionary<string, object> itemsSource = new Dictionary<string, object>();
        itemsSource.Add(Convert.ToString(TextAlignment.Center), TextAlignment.Center);
        itemsSource.Add(Convert.ToString(TextAlignment.Justify), TextAlignment.Justify);
        itemsSource.Add(Convert.ToString(TextAlignment.Left), TextAlignment.Left);
        itemsSource.Add(Convert.ToString(TextAlignment.Right), TextAlignment.Right);

        MultiSelectComboBox.ItemsSource = itemsSource;
    }
}

MultiSelectComboBox的SelectedItems属性将包含用户选择的值。 这是你需要的吗? 如果您使用的是MVVM,则可以使用ViewModel公开ItemsSource和SelectedItems字典。