【发布时间】: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