繁体   English   中英

在Silverlight ComboBox中过滤枚举

[英]Filter enum in Silverlight ComboBox

我有一个代表可能的配置的枚举。 (以下仅是示例...)

public enum ConfigurationType {
    [Description("Minimal Configuration")]
    Minimal = 0,
    [Description("Standard Configuration")]
    Standard,
    [Description("Premium Configuration")]
    Premium
}

现在,我使用值转换器(在此处找到)将类中ConfigurationType类型的属性绑定到ComboBox,以显示Description。 很好 但是,我想做的是能够即时禁用对特定枚举成员的选择,结果是它们不会显示在ComboBox中。

我尝试将这个枚举转换为一个标志枚举,然后绑定到一组标志,但是并没有走得很远。 关于这个或其他建议有什么建议吗?

编辑-标志示例

尝试使用标志时,我将枚举更改为:

[Flags]
public enum ConfigurationType {
    [Description("Minimal Configuration")]
    Minimal = 1 << 0,
    [Description("Standard Configuration")]
    Standard = 1 << 1,
    [Description("Premium Configuration")]
    Premium = 1 << 2
}

public ConfigurationType AvailableConfigs = ConfigurationType.Standard | ConfigurationType.Premium;

它实际上能够将这些按位或列表分配给诸如AvailableConfigs的变量(如上所示),但是值转换器部分是挂断的。 我不确定如何实现一个值转换器来获取AvailableConfigs中每个标志的描述,以及是否能够转换回变量(也属于ConfigurationType),例如SelectedConfiguration。 当然,SelectedConfiguration的设置者每次只强制执行一个标志。

如果可以在XAML中定义可用选项,则可以执行以下操作:

在您的EnumValuesConverter.cs中

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value == null)
        return null;
    else
    {
        if (string.IsNullOrEmpty((string)parameter))
        {
            return EnumValueCache.GetValues(value.GetType());
        }
        return EnumValueCache.GetValues(value.GetType()).Where(x => parameter.ToString().Contains(x.ToString()));
    }
}

并使用如下所示的ConverterParameter进行绑定:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="25,27,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" 
          ItemsSource="{Binding MyEnumProperty, Converter={StaticResource enumConverter}, ConverterParameter=Minimal-Standard}"
          SelectedItem="{Binding MyEnumProperty, Mode=TwoWay}"/>

使用ConverterParameter作为简单的字符串过滤器,它将仅显示MinimalStandard选项。

如果您需要更多动态的东西,那就这么说。 您不能绑定ConverterParameters(不幸的是),因此它将需要更多的工作。

动态特性解决方案

若要使用AvailableConfigs属性执行相同的操作,您将需要实现MultiBinding解决方案(允许您绑定到多个属性)。

绑定的顺序很重要,因为绑定顺序将传递给转换器。

例如

<ComboBox Height="23" HorizontalAlignment="Left" Margin="25,27,0,0" Name="comboBox2" VerticalAlignment="Top" Width="120" >
    <ComboBox.ItemsSource>
        <MultiBinding Converter="{StaticResource enumConverter}">
            <Binding Path="MyEnumProperty" />
            <Binding Path="AvailableConfigs" />
        </MultiBinding>
    </ComboBox.ItemsSource>
</ComboBox>

MultiBinding只是WPF的一部分,而不是Silverlight的一部分,因此这里有一些Silverlight MultiBinding解决方案:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM