c# - 触发 PropertyChanged 时 WPF 依赖属性 setter 未触发,但源值未更改

标签 c# wpf data-binding dependency-properties

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

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

这是个问题,因为我想在 PropertyChanged 上更新自定义文本框(清除文本),即使源属性保持不变。但是,我没有找到任何符合我要求的绑定(bind)选项(有一个 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
        }

最佳答案

XAML 将直接调用 SetValue,而不是调用您的属性 setter 。具体的我记不清了,前段时间遇到过类似的问题。您不应在值的 setter 中放置任何逻辑,而应为依赖属性更改时定义回调,并从那里更新值。

关于c# - 触发 PropertyChanged 时 WPF 依赖属性 setter 未触发,但源值未更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2728267/

相关文章:

c# - IEqualityComparer 和单例

c# - 在 .NET 中添加删除 RegEx 选项

javascript - C#/Javascript session 存储

c# - 为什么不是到处都是 "Try"方法?

wpf - 为什么绑定(bind) TextBlock 文本属性不能按预期工作

wpf - 如何绑定(bind)到数据上下文之外的内容

c# - 显示 SelectedItem 的属性

使用 mvvm 模式的 WPF 数据绑定(bind)问题

c# - 如何避免手动实现 INotifyPropertyChanged

data-binding - zkoss MVVM 更改为模型强制网格重新加载