1

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

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

现在,我正在使用值转换器(在此处ConfigurationType找到)将我的类中的类型属性绑定到 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 的设置器当然会一次只强制执行一个标志。

4

1 回答 1

1

如果您可以在 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 作为简单字符串过滤器的Minimal和选项。Standard

如果您需要更动态的东西,请直说。您无法绑定 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 解决方案:

于 2012-08-01T14:12:51.830 回答