依赖属性GetValue返回null

时间:2016-10-18 10:20:29

标签: c# wpf xaml mvvm dependency-properties

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

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

1 个答案:

答案 0 :(得分:0)

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

在TextChangedTrigger类的构造函数中设置一些值,或者使用允许设置默认值的DependencyProperty.Register重载。

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