本文介绍了如何使DataTemplate.DataTrigger检查大于或小于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 DataTemplate.DataTrigger 如果年龄等于 30,则年龄显示为红色。

The following DataTemplate.DataTrigger makes the age display red if it is equal to 30.

如果年龄大于 30,如何使年龄显示为红色?

How do I make the age display red if it is greater than 30?

<DataTemplate DataType="{x:Type local:Customer}">
    <Grid x:Name="MainGrid" Style="{StaticResource customerGridMainStyle}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="150"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0" Text="First Name" Margin="5"/>
        <TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding FirstName}" Margin="5"/>
        <TextBlock Grid.Column="0" Grid.Row="1" Text="Last Name" Margin="5"/>
        <TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding LastName}" Margin="5"/>
        <TextBlock Grid.Column="0" Grid.Row="2" Text="Age" Margin="5"/>
        <TextBlock x:Name="Age" Grid.Column="1" Grid.Row="2" Text="{Binding Age}" Margin="5"/>
    </Grid>

    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding Path=Age}">
            <DataTrigger.Value>30</DataTrigger.Value>
            <Setter TargetName="Age" Property="Foreground" Value="Red"/> 
        </DataTrigger>
    </DataTemplate.Triggers>

</DataTemplate>


推荐答案

您可以创建 IValueConverter ,它根据 CutOff 将整数转换为布尔值。然后使用 True DataTrigger.Value (或 False

You could create an IValueConverter, which converts an integer to a boolean based on the CutOff. Then use DataTrigger.Value of True (or False, depending on what you are returning).

WPF DataTrigger 严格来说是相等比较器。

WPF DataTriggers are strictly equality comparers if I remember correctly.

类似于以下内容:

public class CutoffConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        return ((int)value) > Cutoff;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        throw new NotImplementedException();
    }

    public int Cutoff { get; set; }
}

然后使用以下XAML。

Then use the following XAML.

<Window.Resources>
    <myNamespace:CutoffConverter x:Key="AgeConverter" Cutoff="30" />
</Window.Resources>

<DataTemplate.Triggers>
    <DataTrigger Binding="{Binding Path=Age,
                                   Converter={StaticResource AgeConverter}}">
        <DataTrigger.Value>true</DataTrigger.Value>
        <Setter TargetName="Age" Property="Foreground" Value="Red"/> 
    </DataTrigger>
</DataTemplate.Triggers>

这篇关于如何使DataTemplate.DataTrigger检查大于或小于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 11:59