使用3个组合框选择项值控制按钮启用状态

时间:2016-08-29 10:08:45

标签: c# wpf xaml

我正在开发一个WPF应用程序。我有3个组合框。每个组合框都有一个List作为源,有3个项目:每个组合框中有1,2,3个。 我也有一个按钮。如果用户在至少2个组合框中选择了相同的值,我想禁用该按钮。 IE浏览器。如果用户在第一个CB中选择1,在第二个CB中选择1,则禁用该按钮。我试图使用按钮内的下面的代码来实现这一点。 但无论如何它都不起作用。

<Button>
....
<Style> 
    <Style.Triggers>
        <MultiDataTrigger>
            <MultiDataTrigger.Conditions>
                <Condition Binding="{Binding ElementName=CB1, Path=SelectedItem}" Value="1" />
                <Condition Binding="{Binding ElementName=CB2, Path=SelectedItem}" Value="1" />
                <Condition Binding="{Binding ElementName=CB3, Path=SelectedItem}" Value="1" />
            </MultiDataTrigger.Conditions>
            <Setter Property="IsEnabled" Value="False" />
        </MultiDataTrigger>
    </Style.Triggers>
</Style>
</Button>

你能否建议一个更好的解决方案,在XAML本身做同样的事情?

1 个答案:

答案 0 :(得分:0)

我会使用MultiValueConverter来实现这一目标:

public class IsDistinctConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.Distinct().Count() == values.Length;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

如果传递列表中的所有项都是唯一的,Convert方法将返回true。在XAML中,您可以像这样使用转换器:

<Button Content="My Button">
    <Button.Resources>
        <!-- You can move this Resource to another place without any problem -->
        <local:IsDistinctConverter x:Key="IsDistinctConverter"/>
    </Button.Resources>
    <Button.IsEnabled>
        <MultiBinding Converter="{StaticResource IsDistinctConverter}">
            <Binding Path="SelectedItem" ElementName="CB1"/>
            <Binding Path="SelectedItem" ElementName="CB2"/>
            <Binding Path="SelectedItem" ElementName="CB3"/>
        </MultiBinding>
    </Button.IsEnabled>
</Button>