我的UserControl中有几个TextBlocks,我想要更改为Bold,并在触发Property时使用Red字体。问题是每个都被不同的属性改变。我看到了一个带有标签的解决方案here,但无法让它适合我。如果这是重复,我道歉,但我找不到解决问题的任何解决方案。
我的风格如下:
<Style x:Key="TextBlockTrigger" TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property="Tag" Value="true">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
这就是我尝试使用它的TextBlock:
<TextBlock Name="TextBlock1" x:Uid="TextBlock1" Text="This text should become bold and Red"
Style="{StaticResource TextBlockTrigger}" Tag="{Binding Path=TriggerProperty, UpdateSourceTrigger=PropertyChanged}"/>
我添加了一个带有代码隐藏功能的按钮,用于读取标记,断点显示Tag设置为true,但文本仍然是常规的黑色。
在InitializeComponent之后,在View构造函数中通过函数调用设置TriggerProperty:
public MyWindow()
{
InitializeComponent();
UpdateServerProperties();
}
public void UpdateServerProperties()
{
//other code
if(ServerValue == true)
{
TriggerProperty = true;
OnPropertyChanged("TriggerProperty");
}
}
它有点简化,但实际代码过于复杂,但结果相同。 ServerValue获取一个值,我已确认TriggerProperty确实更新为true。
答案 0 :(得分:2)
Tag
属性的类型为object
。 Xaml无法知道true
代表bool
值,因此它假设您认为它是string
。假设您将Tag
设置为布尔值,则Trigger
正在评估Equals(true, "true")
,因此条件失败。
尝试使用{x:Static}
指向某个常量布尔值。我为这类事做了KnownBoxes
课:
public static class KnownBoxes
{
public static readonly object True = true;
public static readonly object False = false;
// ... more common values ...
}
可以从Xaml轻松引用这些值,例如{x:Static ns:KnownBoxes.True}
。
或者,您可以使用元素语法:
<Trigger Property="Tag">
<Trigger.Value>
<s:Boolean xmlns:s="clr-namespace:System;assembly=mscorlib">True</s:Boolean>
</Trigger.Value>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="Red"/>
</Trigger>
或者您可以将Tag
设置为字符串"true"
,但是当其他人处理您的代码时,这可能会造成一些混淆:)。
答案 1 :(得分:1)
如果在运行时动态地将TriggerProperty
设置为true
,则定义此属性的类应实现INotifyPropertyChanged接口,并将触发器的PropertyChanged
事件提升为触发。
如果将Tag
属性设置为硬编码值true
,则示例标记应按预期工作:
<TextBlock Name="TextBlock1" x:Uid="TextBlock1" Text="This text should become bold and Red"
Style="{StaticResource TextBlockTrigger}" Tag="true"/>
您还应该将Value
属性设置为bool
中的已键入Style
值:
<Style x:Key="TextBlockTrigger" TargetType="{x:Type TextBlock}"
xmlns:s="clr-namespace:System;assembly=mscorlib">
<Style.Triggers>
<Trigger Property="Tag">
<Trigger.Value>
<s:Boolean>True</s:Boolean>
</Trigger.Value>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>