Как привязать к чужому свойству объекта с помощью шаблона стиля XAML? - PullRequest
0 голосов
/ 01 апреля 2019

Допустим, у меня есть следующий класс:

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 Template Trigger на основе свойства HasFocus, поэтому я делаю следующее:

<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 Ответ

2 голосов
/ 01 апреля 2019

Элемент в шаблоне, который применяется к TextBox, не может быть привязан к свойству MyClass, если только нет элемента MyClass для привязки где-либо в визуальном дереве.

Если вы хотите установить пользовательское свойство HasFocus для TextBox, вам нужно создать присоединенное свойство :

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>
...