WPF依赖属性的setter在触发PropertyChanged时未触发,但源值未更改。

5
我在自定义的 Textbox 上有一个 int 类型依赖属性,它保存一个后备值。它与 DataContext 中的一个 int? 类型属性进行了绑定。
如果我在 DataContext 中引发了 PropertyChanged 事件,但源属性的值没有更改(仍为 null),则依赖属性的 setter 不会被触发。
这是个问题,因为我想在 PropertyChanged 时更新自定义 Textbox(清除文本),即使源属性保持不变。然而,我没有找到任何可以实现我的需求的绑定选项(虽然有 UpdateSourceTrigger 属性,但我想在此处更新目标,而非源)。
也许有更好的方法来通知 Textbox 需要清除其文本,我对任何建议都持开放态度。
如请求的那样,以下是简化版的源代码:
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
即使源相同,它也应该更新。发布您的代码,解决方案应该很容易发现。 - Aurelien Ribon
我发布了一些代码。这个应用程序太复杂了,无法在此处包含整个源代码。名称已被替换。 - Sandor Davidhazi
1个回答

16

XAML会直接调用SetValue方法,而不是调用你的属性设置器。我记不清具体细节了,但我之前遇到过类似的问题。你不应该在Value的设置器中放置任何逻辑,而是定义一个回调函数,用于当依赖属性改变时更新值。


太好了!我一直在寻找为什么我的设置逻辑没有被执行。 - Ignacio Soler Garcia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接