C# 具有特定触发器值的通用样式
我的UserControl中有几个文本块,我想在触发属性时将其更改为粗体并使用红色字体。问题是,它们中的每一个都被不同的属性所改变。我看到了一个带有标签的解决方案,但无法完全让它为我工作。如果这是重复的,我很抱歉,但是我找不到任何解决问题的方法 我的风格是这样的:C# 具有特定触发器值的通用样式,c#,wpf,xaml,C#,Wpf,Xaml,我的UserControl中有几个文本块,我想在触发属性时将其更改为粗体并使用红色字体。问题是,它们中的每一个都被不同的属性所改变。我看到了一个带有标签的解决方案,但无法完全让它为我工作。如果这是重复的,我很抱歉,但是我找不到任何解决问题的方法 我的风格是这样的: <Style x:Key="TextBlockTrigger" TargetType="{x:Type TextBlock}"> <Style.Triggers> <Trigger Prope
<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>
它有点简化,但实际代码过于复杂,但结果是相同的。ServerValue获取一个值,我已确认TriggerProperty确实更新为true。如果在运行时将
TriggerProperty
动态设置为true
,则定义此属性的类应实现接口并引发PropertyChanged
事件以触发触发器
如果将标记
属性设置为硬编码值true
,则示例标记应按预期工作:
<TextBlock Name="TextBlock1" x:Uid="TextBlock1" Text="This text should become bold and Red"
Style="{StaticResource TextBlockTrigger}" Tag="true"/>
标记
属性具有对象
类型。Xaml无法知道true
表示一个bool
值,所以它只是假设您的意思是一个字符串。假设将标记设置为布尔值,则触发器正在计算等于(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>
真的
或者,您可以将标记设置为字符串的“true”
,但当其他人处理您的代码时,这可能会造成一些混乱:)。是否动态设置TriggerProperty属性?您是否实现了INotifyPropertyChanged?我已经实现了INotifyPropertyChanged,并使用该属性触发其他xaml块的可见性,例如:
使用Tag=“true”
将文本更改为红色。但正如我所说,我添加了一个按钮,触发了一个Codebehind函数,我在其中读取断点中的标记,它从绑定中得到的值为true,所以我不理解这一点。如何以及在哪里设置TriggerProperty?请包括一些代码来演示这一点。我在帖子中添加了简化。实际代码对于SO帖子来说太长了,而且几乎所有的代码都是无关的。Mike Strobel建议同样的,它工作得很好,谢谢!使用s:Boolean
成功了!第二个选项是将标记设置为“true”
,但我需要为此制作一个BooleanToStringConverter。这要简单得多,谢谢!
<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>
public static class KnownBoxes
{
public static readonly object True = true;
public static readonly object False = false;
// ... more common values ...
}
<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>