如何灰化某些组合框项目,应该阻止选择

时间:2016-12-19 12:55:50

标签: wpf

我有两个字符串集合。第一个集合设置为itemsource,其他集合包含要禁用的项目。我的组合框如下所示。

<ComboBox Name="txtToolName" HorizontalAlignment="Left" Height="23" Margin="10,42,0,0" 
             VerticalAlignment="Top" Width="260" 
             Grid.Column="1" >
    </ComboBox>

如何显示带有禁用项目的组合框。不应选择禁用的项目。

2 个答案:

答案 0 :(得分:1)

您不应该使用两个单独的集合。而是创建一个集合,其中项目数据和可选信息被组合在一起。

IEnumerable<string> entries;
IEnumerable<string> disabled;
txtToolName.ItemsSource = entries.Select(x => new { Value = x, IsSelectable = !disabled.Contains(x) }).ToList();

请注意,此匿名类型Select仅用于演示目的。您应该为组合数据使用一些合适的类型。

您可以将ComboBoxItem属性IsEnabled设置为False,以禁用选择。

<ComboBox Name="txtToolName" SelectedValuePath="Value" DisplayMemberPath="Value">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="IsEnabled" Value="{Binding IsSelectable}"/>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

答案 1 :(得分:0)

如果您出于某种原因依赖于拥有两个单独的集合,那么如果将ComboBox的ItemsSource属性设置为包含两个集合的CompositeCollection,您仍然可以执行此操作:

public MainWindow()
{
    InitializeComponent();

    List<string> yourEnabledCollection = new List<string> { "a", "b", "c" };
    enabledItems.Collection = yourEnabledCollection.Select(s => new { Value = s, IsEnabled = true });

    List<string> yourDisabledCollection = new List<string> { "d", "e", "f" };
    disabledItems.Collection = yourDisabledCollection.Select(s => new { Value = s, IsEnabled = false });
}
<ComboBox Name="txtToolName" HorizontalAlignment="Left" Height="23" Margin="10,42,0,0"
                  DisplayMemberPath="Value">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="IsEnabled" Value="{Binding IsEnabled, Mode=OneTime}"/>
        </Style>
    </ComboBox.ItemContainerStyle>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <CollectionContainer x:Name="enabledItems" />
            <CollectionContainer x:Name="disabledItems" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>