【问题标题】:Dependency Property GetValue returns null依赖属性 GetValue 返回 null
【发布时间】:2016-10-18 10:20:29
【问题描述】:

我在我的 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?

【问题讨论】:

  • 使用object test = TextChangedCommand;怎么样?
  • @MikeEason 它不起作用
  • 看我的回答。我编辑了它

标签: c# wpf xaml mvvm dependency-properties


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2018-12-11
    相关资源
    最近更新 更多