2010-04-28 225 views
5

我在自定义文本框上有一个int依赖项属性,该属性包含一个备用值。它绑定到一个int? DataContext上的属性。当PropertyChanged被触发时,WPF依赖项属性设置器未触发,但源值未更改

如果我在DataContext中引发PropertyChanged事件,并且源属性的值未更改(保留为空),则不会触发依赖项属性的setter。

这是一个问题,因为我想更新PropertyChanged上的自定义文本框(清除文本),即使源属性保持不变。但是,我没有找到任何我想要的绑定选项(有一个UpdateSourceTrigger属性,但我想在此更新目标,而不是源)。 也许有一个更好的方式来通知文本框,它需要清除它的文本,我愿意接受任何建议。

源,如请求的(简化的)

DataContext的(源):

private int? _foo; 

    public int? Foo 
    { 
     get 
     { 
      // The binding is working, because _foo is retrieved (hits a breakpoint here). 
      // RaisePropertyChanged("Foo") is called from elsewhere, even if _foo's value is not changed 
      return _foo; 
     } 
     set 
     { 
      // Breakpoint is hit on user input, so the binding is working 
      _foo = value; 
      RaisePropertyChanged("Foo"); 
     } 
    } 

自定义文本框(目标):

public double? Value 
{ 
    get 
    { 
     return (double?)GetValue(ValueProperty); 
    } 
    set 
    { 
      // When Foo is null and Value is also null, the breakpoint is not hit here 
      SetValue(ValueProperty, value); 

      // This is the piece of code that needs to be run whenever Value is set to null 
      if (value == null && !String.IsNullOrEmpty(Text)) 
      { 
       Text = String.Empty; 
      } 
     } 
    } 

    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double?), typeof(CustomTextbox), new PropertyMetadata(null, ValueChangedHandler)); 

    private static void ValueChangedHandler(DependencyObject dependecyObject, DependencyPropertyChangedEventArgs e) 
     { 
      // When Foo is null and Value is also null, the breakpoint is not hit here 
     } 
+1

你能发表一些代码吗?这会让你更容易理解你的问题。你在DataContext中究竟如何提升PropertyChanged事件? – wpfwannabe 2010-04-28 09:45:57

+0

即使源代码相同,它也应该更新。发布你的代码,解决方案应该很容易被发现。 – 2010-04-28 09:54:29

+0

我发布了一些代码。该应用程序太复杂,无法在此处包含整个源代码。名称已被替换。 – 2010-04-28 12:24:45

回答

16

的XAML将直接调用的SetValue,而不是调用你的财产制定者。我不记得具体的细节,但我前一段时间碰到类似的问题。你不应该在Value的setter中放置任何逻辑,而应该为依赖属性更改时的回调定义一个回调,并从那里更新值。

+0

太棒了!我在寻找为什么我的逻辑没有被执行。 – 2011-10-12 17:03:27

+0

+1 - 谢谢瓦莱丽,你救了我的一天! – 2012-05-16 14:01:29