依赖属性GetValue返回null

本文关键字:null 返回 GetValue 属性 依赖 | 更新日期: 2023-09-27 18:13:26

我在XAML中声明了一个自定义TriggerAction,并将Command绑定到它。

<DataTemplate x:Key="data">
        <StackPanel Orientation="Vertical">
            <TextBlock Text="{Binding Name}"/>
            <TextBox Width="150" Name="styleTb">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="TextChanged">
                        <behaviors:TextChangedTrigger TextChangedCommand="{Binding TextChangedCommand}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </TextBox>
        </StackPanel>
    </DataTemplate>

但是当我试图通过GetValue方法获得值时,它返回null

这是类的样子

public class TextChangedTrigger : TriggerAction<TextBox>
{
    public static readonly DependencyProperty TextChangedCommandProperty = DependencyProperty.Register("TextChangedCommand", typeof(ICommand),
                                                                                                        typeof(TextChangedTrigger));
    /// <summary>
    /// Gets the Command which will be executed.
    /// </summary>
    public  ICommand TextChangedCommand
    {
        get { return (ICommand)GetValue(TextChangedCommandProperty); }
        set { SetValue(TextChangedCommandProperty, value); }
    }
    /// <summary>
    /// Invokes the TextChangedCommand
    /// </summary>
    /// <param name="parameter"></param>
    protected override void Invoke(object parameter)
    {
        object test = GetValue(TextChangedCommandProperty); // Returns null
    }

为什么返回null?

依赖属性GetValue返回null

您从未实际设置TextChangedCommand属性的值为任何值。

要么在TextChangedTrigger类的构造函数中设置它的某个值,要么使用DependencyProperty。允许设置默认值的寄存器重载。

public static readonly DependencyProperty TextChangedCommandProperty = DependencyProperty.Register("TextChangedCommand",
    typeof(ICommand),
    typeof(TextChangedTrigger),
    new UIPropertyMetadata(new WhateverYourCommandIs());