簡體   English   中英

如何在WPF中進行條件DataTrigger

[英]How to make conditional DataTrigger in WPF

我想使用WPF中的style在datagrid中為DataGridRow着色。 我想根據價值確定着色百分比。 如果我具有0到50之間的值綁定Error ,它將為紅色。 反之亦然,將其顯示為綠色

但是我該如何處理樣式?

 <Style TargetType="DataGridRow">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Error}" Value="Error>50"> //maybe something like this
                        <Setter Property="Foreground" Value="#FFE08F8F" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Error}" Value="2">
                        <Setter Property="Foreground" Value="#FF6DBB6D" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>

您將需要一個自定義轉換器,該轉換器將Error轉換為指示錯誤狀態的某個值。 Error大於50時,以下轉換器將返回True

public class ErrorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return System.Convert.ToInt(value) > 50;
    }

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

現在在資源中引用它( True幫助器,您可能不需要它,不記得轉換是否是自動的):

<system:Boolean x:Key="True">True</system:Boolean>
<local:ErrorConverter x:Key="ErrorConverter">

並像這樣綁定它:

<Style TargetType="DataGridRow">
    <Style.Triggers>
        <DataTrigger 
            Binding="{Binding Error, Converter={StaticResource ErrorConverter}}" 
            Value="{StaticResource True}">
            <Setter Property="Foreground" Value="#FFE08F8F" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Error}" Value="2">
            <Setter Property="Foreground" Value="#FF6DBB6D" />
        </DataTrigger>
    </Style.Triggers>
</Style>

遵循這些原則的東西應該起作用。

IMO最靈活的解決方案是添加某種ErrorToColor轉換器。 然后使用此XAML:

<Setter Property="Foreground" >
    <Setter.Value>
        <SolidColorBrush Color="{Binding Error, Converter={StaticResource errorToColorConverter}}" />
    </Setter.Value>
</Setter>

這樣的轉換器看起來像這樣:

public class IntToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {            
        return value is int && ((int)value) > 50 ? Colors.Green : Colors.Red;
    }

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

這樣,您可以輕松管理不同誤差值的顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM