繁体   English   中英

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

[英]How to bind to another's object property with XAML Style Template?

假设我有以下课程:

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

我想通过基于属性HasFocus XAML模板触发器更改TextBox一些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定义还可以。

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

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

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

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM