检查触发器属性 XAML 中的值范围
本文关键字:范围 XAML 触发器 属性 检查 | 更新日期: 2023-09-27 18:28:31
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property="Text" Value="1">
<Setter Property="Background" Value="LightGreen"/>
<Setter Property="Foreground" Value="LightGreen"/>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
上面的代码将背景和前景属性设置为"浅绿色",如果文本块包含值"1",是否可以在触发器中检查一系列 intiger 值,例如,如果文本块值从 1 - 10,则背景和前景属性需要更改为浅绿色。
试试这段代码
转炉
/// <summary>
/// The actual implementation of InverseBooleanVisibilityConverter
/// </summary>
internal class RangeConverter : IValueConverter
{
/// <summary>
/// Converters the Boolean value to Visibility inversely
/// </summary>
/// <param name="value">The Boolean value</param>
/// <param name="targetType">The target value</param>
/// <param name="parameter">The parameter</param>
/// <param name="culture">The culture of the value</param>
/// <returns>Returns the a Visibility Type Value</returns>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int j;
Int32.TryParse(value as string, out j);
if (j <= 10)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Converters the Visibility value to Boolean inversely
/// </summary>
/// <param name="value">The Boolean value</param>
/// <param name="targetType">The target value</param>
/// <param name="parameter">The parameter</param>
/// <param name="culture">The culture of the value</param>
/// <returns>Returns the a Visibility Type Value</returns>
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cef="clr-namespace:WpfApplication1"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="Window1" x:Name="testWindow" Height="500" Loaded="Window_Loaded" Width="300" >
<Window.Resources>
<cef:RangeConverter x:Key="rangeConv"></cef:RangeConverter>
</Window.Resources>
<Grid >
<StackPanel x:Name="stk">
<TextBlock Text="1" Width="100">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource ResourceKey=rangeConv}}" Value="True">
<Setter Property="TextBlock.Foreground" Value="LimeGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
</Grid>
</Window>
您应该使用自定义转换器来实现这一点,请阅读以下文章
https://social.msdn.microsoft.com/Forums/vstudio/en-US/a8ad8c14-95aa-4ed4-b806-d0ae874a8d26/conditional-triggers?forum=wpf