如何使用XAML样式模板绑定到另一个对象属性?

问题描述 投票:0回答:1

假设我有以下课程:

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; }
}

我想基于属性TextBox通过XAML模板触发器更改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定义没问题。

任何想法如何解决这个问题?

c# wpf dependency-properties
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.