2014-07-15 54 views
0

我已经这样绑定 - 回调被调用两次

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)。用户控件绑定到查看与数据模板模型(也许这很重要)

而且这是在用户控制

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

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

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

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

虽然双枪不是一个真正的问题,它打扰我。用null回调价值是我真正的问题(我认为他们是相关的)。任何人都知道什么是错的?


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

需要帮助时,ContentControl中视图模型改变

的PropertyChanged回调调用默认值。

这意味着nullText在我的情况。任何人?我无法弄清楚它为什么叫。如果可以这样说的话,我的猜测是DataTemplate经理。

回答

-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("")); 
+0

但是..但是..我需要回调(做一些逻辑和动画)。您是否可能知道其他解决方案以了解依赖项属性值更改的时间? – Sinatr

+0

我认为编写你的逻辑时ProgressText(调用OnPropertyChanged();)的变化比编写它时更容易DependencyProperty –

+0

ProgressText属于视图模型(另一类),这是不可能的。我应该用'MVVM'来标记问题,对不起。 – Sinatr