在 Style 中触发自定义依赖属性 [英] Trigger for custom dependency properties in Style
问题描述
我定义了一个可重用控件 MyControl,它扩展了一个 TextBox.
I defined a reusable control, MyControl, that extends a TextBox.
我想将触发器设置为其依赖属性之一.
所以我给它添加了一个样式,带触发器.
I want to set a Trigger to one of its dependency properties.
So I added a style to it, with Triggers.
但是,如果我将 Style 的 TargetType 设置为 MyControl,则会收到 XAML 警告,指出 'MyControl' TargetType 与元素类型 'TextBlock'
不匹配.
如果我将它设置为 TextBlock,我会收到一个编译错误:无法识别或无法访问成员MyDependencyProperty".
.
But if I set the TargetType of the Style to MyControl, I get a XAML warning that 'MyControl' TargetType does not match type of element 'TextBlock'
.
And if I set it to TextBlock, I get a compilation error that The member "MyDependencyProperty" is not recognized or is not accessible.
.
- 如何使用触发器定义这种样式?
namespace UserControls.Local
{
public partial class MyControl : TextBlock
{
#region Trogdor
public static readonly DependencyProperty TrogdorProperty = DependencyProperty.Register(
"Trogdor", typeof (bool), typeof (MyControl), new PropertyMetadata(default(bool)));
public bool Trogdor
{
get { return (bool) GetValue(TrogdorProperty); }
set { SetValue(TrogdorProperty, value); }
}
#endregion
public MyControl()
{
InitializeComponent();
}
}
}
XAML
<TextBlock
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:UserControls.Local"
mc:Ignorable="d"
Text="BOOP!"
x:Class="UserControls.Local.MyControl">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Trogdor" Value="True">
<Setter Property="Foreground" Value="DeepPink"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
推荐答案
我找到的解决方案是完全限定"绑定上的依赖属性:
The solution I found was to "fully qualify" the dependency property on the binding:
<Trigger Property="local:MyControl.Trogdor" Value="True">
这篇关于在 Style 中触发自定义依赖属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!