基于标签内容中未知索引处的字符的 WPF 标签样式触发器,是否可能? [英] WPF Label Style Trigger based on a char at unknown index in Contents of the Label, is it possible?
问题描述
当表单上的字段要求发生变化时,与其以编程方式设置样式,不如使用触发器来检查 Label.Contents 中的最后一个字符是否为*",如果是,则在标签?
Rather than programatically set the the style when the requirement of a field on a form changes is it possible to use a trigger that checks the last char in a Label.Contents is a '*' and if so set a property on the Label?
类似这样,但如何检查 Content 属性的最后一个字符?
Something like this but how to check on the last char of the Content property?
<Style x:Key="LabelStandard" TargetType="Label">
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Top"/>
<Style.Triggers>
<Trigger Property="Content" Value="*"> <!-TODO only check the last char -->
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
推荐答案
我认为您必须为此使用转换器.尝试这样的事情
I think you'll have to use a Converter for that. Try with something like this
<Style x:Key="LabelStandard" TargetType="Label">
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Top"/>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource self},
Path=Content,
Converter={StaticResource LastCharConverter},
ConverterParameter=*}"
Value="True">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
public class LastCharConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
{
return false;
}
string content = value.ToString();
if (content.Length > 0 &&
content[content.Length - 1] == (char)parameter)
{
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
更新
您可以绑定到 Content
字符串中的任何给定字符,只要您知道它的位置.
You can bind to any given character in the Content
string as long as you know its position.
<Style x:Key="LabelStandard" TargetType="Label">
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Top"/>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource self},
Path=(Content)[2]}"
Value="*">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
但是,如果您的字符串长度会有所不同(我认为是这种情况),那对您没有多大好处,因为您无法在绑定中绑定 [2]
(以任何方式)我知道).
But if your string length will vary (which I assume is the case) that won't do you much good since you can't bind the [2]
inside the binding (in any way that I'm aware of).
除此之外,我认为您必须像您自己指出的那样在解决方案背后编写代码
Other than this, I think you'll have to do a code behind solution as you pointed out yourself
这篇关于基于标签内容中未知索引处的字符的 WPF 标签样式触发器,是否可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!