【问题标题】:WPF dependency property setter not firing when PropertyChanged is fired, but source value is not changed触发 PropertyChanged 时 WPF 依赖项属性设置器未触发,但源值未更改
【发布时间】:2011-02-13 06:29:30
【问题描述】:

我的自定义文本框上有一个 int 依赖属性,它包含一个支持值。它绑定到一个int? DataContext 上的属性。

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

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

来源,根据要求(简化)

数据上下文(来源):

  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
        }

【问题讨论】:

  • 你能贴一些代码吗?这将使您更容易理解您的问题。您究竟是如何在 DataContext 中引发 PropertyChanged 事件的?
  • 即使来源相同,它也应该更新。发布您的代码,解决方案应该很容易发现。
  • 我发布了一些代码。该应用程序过于复杂,无法在此处包含整个源代码。名称已被替换。

标签: c# wpf data-binding dependency-properties


【解决方案1】:

XAML 将直接调用 SetValue,而不是调用您的属性设置器。我不记得确切的细节,但前段时间我遇到了类似的问题。您不应该在 Value 的 setter 中放置任何逻辑,而是在 Dependency Property 更改时定义一个回调,并从那里更新值。

【讨论】:

  • 太棒了!我正在寻找为什么我在片场的逻辑没有被执行。
猜你喜欢
  • 2011-08-04
  • 2011-02-08
  • 2014-06-14
  • 2014-04-08
  • 2021-11-08
  • 2016-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多