我的自定义文本框有一个 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/