如何使用XAML样式模板绑定到他人的对象属性?

时间:2019-04-01 06:36:12

标签: c# wpf dependency-properties

假设我有以下课程:

public class MyClass : System.Windows.FrameworkElement
{
    public static readonly DependencyProperty HasFocusProperty = DependencyProperty.RegisterAttached("HasFocus", typeof(bool), typeof(MyClass), new PropertyMetadata(default(bool)));

    public bool HasFocus
    {
        get => (bool)GetValue(HasFocusProperty);
        set => SetValue(HasFocusProperty, value);
    }

    public System.Windows.Controls.TextBox TextBox { get; set; }
}

我想通过XAML模板触发器基于属性TextBox来更改HasFocus的某些UI属性,因此我要执行以下操作:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:win="clr-namespace:System.Windows.Controls">
    <Style TargetType="{x:Type win:TextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type win:TextBox}">
                    <ControlTemplate.Triggers>
                        <Trigger Property="MyClass.HasFocus" Value="True">
                            <Setter TargetName="Border" Property="BorderBrush" Value="Red" />
                            <Setter TargetName="Border" Property="BorderThickness" Value="2" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
 </ResourceDictionary>

但是,设置HasFocus = true时不会应用样式。

TextBox的属性中,我看到触发器已注册。如果我将<Trigger Property="MyClass.HasFocus" Value="True">更改为<Trigger Property="MyClass.HasFocus" Value="False">,则会首先应用我的样式。所以我认为我的XAML定义还可以。

有什么办法解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

除非将TextBox元素绑定到可视树中的某个位置,否则模板中应用于MyClass的元素不能绑定到MyClass的属性。

如果您希望能够设置HasFocus的自定义TextBox属性,则应创建一个attached property

public class FocusExtensions
{
    public static readonly DependencyProperty SetHasFocusProperty = DependencyProperty.RegisterAttached(
        "HasFocus",
        typeof(bool),
        typeof(FocusExtensions),
        new FrameworkPropertyMetadata(false)
    );

    public static void SetHasFocus(TextBox element, bool value)
    {
        element.SetValue(SetHasFocusProperty, value);
    }

    public static bool GetHasFocus(TextBox element)
    {
        return (bool)element.GetValue(SetHasFocusProperty);
    }
}

可以为任何TextBox元素进行设置:

<TextBox local:FocusExtensions.HasFocus="True">
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="local:FocusExtensions.HasFocus" Value="True">
                    <Setter Property="BorderBrush" Value="Red" />
                    <Setter Property="BorderThickness" Value="2" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>