触发样式中的自定义依赖项属性

ANe*_*ves 4 wpf xaml

问题

我定义了一个可重用的控件MyControl,它扩展了TextBox。

我想将触发器设置为其依赖项属性之一。
因此,我使用触发器向其添加了样式。

但是,如果我将样式的TargetType设置为MyControl,则会收到XAML警告'MyControl' TargetType does not match type of element 'TextBlock'
并且,如果将其设置为TextBlock,则会出现编译错误,即The member "MyDependencyProperty" is not recognized or is not accessible.

  • 如何使用触发器定义此样式?

样品

C#代码隐藏

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

ANe*_*ves 5

我发现的解决方案是“完全限定”绑定上的依赖项属性:

<Trigger Property="local:MyControl.Trogdor" Value="True">
Run Code Online (Sandbox Code Playgroud)