【问题标题】:Binding - callback is called twice绑定 - 回调被调用两次
【发布时间】:2014-07-15 13:42:22
【问题描述】:

我有一个像这样的依赖属性的简单控件

public class StatusProgress : Control
{
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(StatusProgress),
        new FrameworkPropertyMetadata(null, (d, e) => (d as StatusProgress).TextUpdated(e.OldValue as string)));

    private void TextUpdated(string text)
    {
        Trace.WriteLine("test");
    }
}

然后我有视图模型

public class ViewModelPageAnalyse : ViewModelPageBase
{

    private string _progressText;
    public string ProgressText
    {
        get { return _progressText; }
        set
        {
            _progressText = value;
            OnPropertyChanged(); // base class INotifyPropertyChanged implementation
        }
    }
}

然后是一个用户控件(显示在带有ContentControl 的窗口中)。用户控件绑定到带有数据模板的视图模型(也许这很重要)

<DataTemplate DataType="{x:Type local:ViewModelPageAnalyse}">
    <local:UserControlAnalyse/>
</DataTemplate>

这是用户控件中的控件

<local:StatusProgress Text="{Binding ProgressText}"/>

现在是有趣的部分。当视图模型中的ProgressText 被设置/更改时,属性更改回调被调用两次。我在调试器输出窗口中看到了两次"test"

更有趣的是:当视图改变时,由于某种原因,回调再次调用e.NewValue = null,而没有直接将ProgressText设置为null

我已经尝试在上升事件之前检查 ProgressText 设置器中的值是否已更改,尝试单向设置绑定模式,但问题仍然存在 - 回调被调用两次,具有相同的值,调用堆栈看起来相同,但有在 wpf 中确实有很多电话可以确定。

虽然双重射击不是一个真正的问题,但它困扰着我。使用null 值回调是我真正的问题(我认为它们是相关的)。有谁知道怎么回事?


找到第一个问题的原因:它是Content的其他控件。在过渡期间,它创建了一个新的Model(因为ContentViewModel)而不是重新分配现有的用户控件。完全是我的错。第二个问题仍然存在,我发现了this 问题(解决方法不适合我)。

需要帮助

当 ContentControl ViewModel 改变时,PropertyChanged 回调被调用,默认值。

在我的情况下,这意味着 null 代表 Text。任何人?我不知道为什么叫它。我猜它是由DataTemplate 经理调用的,如果我可以这么说的话。

【问题讨论】:

    标签: c# wpf mvvm binding callback


    【解决方案1】:

    尝试改变这一行:

      public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(StatusProgress),
        new FrameworkPropertyMetadata(null, (d, e) => (d as StatusProgress).TextUpdated(e.OldValue as string)));
    

    用这个:

        public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(StatusProgress)
        , new PropertyMetadata(""));  
    

    【讨论】:

    • 但是.. 但是.. 我需要回调(做一些逻辑和动画)。您是否可能知道其他解决方案来了解依赖属性值何时更改?
    • 我认为在 ProgressText (在调用 OnPropertyChanged(); 之前)更改时编写逻辑比在 DependencyProperty 更改时编写逻辑要容易
    • ProgressText 属于视图模型(另一个类),这是不可能的。我应该用MVVM 标记这个问题,对不起。
    猜你喜欢
    • 1970-01-01
    • 2015-04-23
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多