数据触发条件检查WPF

时间:2013-12-26 06:58:45

标签: c# wpf xaml setter datatrigger

如果有可能在DataTrigger上给出条件吗?

<DataTrigger Binding="{Binding MessageBoxImage}" Value="{x:Static MessageBoxImage.Error}">
    <Setter Property="Source" Value="../Images/Error48.png"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding MessageBoxImage}" Value="{x:Static MessageBoxImage.Hand}">
    <Setter Property="Source" Value="../Images/Error48.png"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding MessageBoxImage}" Value="{x:Static MessageBoxImage.Stop}">
    <Setter Property="Source" Value="../Images/Error48.png"></Setter>
</DataTrigger>

所以,这是我的Xaml代码,其中Error,Hand,Stop all都设置了相同的图像

我的问题是有可能给这三个值的OR条件吗? (或一行声明)

谢谢,

2 个答案:

答案 0 :(得分:2)

您可以将MultiDataTrigger用于AND条件。至于OR条件,你可以使用转换器。

<Window.Resources>
   <someNs:ORConverter x:Key = "ORConverter"/>
</Window.Resources>

....

<DataTrigger Value="True">
   <DataTrigger.Binding>
        <Binding Path="MessageBoxImage" Converter="{StaticResource ORConverter}">
            <Binding.ConverterParameter>
                <x:Array Type="MessageBoxImage">
                     <x:Static MemberType="MessageBoxImage" Member="Error" />
                     <x:Static MemberType="MessageBoxImage" Member="Information" />
                     <x:Static MemberType="MessageBoxImage" Member="Question" />
                </x:Array>
            </Binding.ConverterParameter>
        </Binding>
   </DataTrigger.Binding>

   <Setter Property="Source" Value="../Images/Error48.png"></Setter>
</DataTrigger>

转换器的代码:

public class ORConverter : IValueConverter
{
    public object Convert(object value, Type targetType, 
           object parameter, System.Globalization.CultureInfo culture)
    {
         var list = parameter as IList;
         if (list == null)
             return false;

         foreach (var o in list)
         {
             if (Equals(o, value))
                return true;
         }

         return false;
    }

    public object ConvertBack(object value, Type targetType, 
           object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException("Cannot convert back");
    }
}

答案 1 :(得分:0)

简单的DataTrigger用于检查单个值。如果可能,您可以使用Multi-DataTrigger检查多个条件。