我正在为自定义依赖属性烦恼不已。我已经查看了很多相关的帖子,但是还没有找到解决方案。我的目标是,如果源提供了特定的值(例如给定示例中的null),则替换属性的值。无论我尝试什么方法,在源中的属性值始终保持为null,从未更新。
这是我的自定义控件:
记住:我需要双向绑定,所以 OneWayToSource 对我没用。
你知道我漏掉了什么吗?
这是我的自定义控件:
public class TextBoxEx : TextBox
{
public TextBoxEx()
{
TrueValue = 0;
this.TextChanged += (s, e) =>
{
TrueValue = Text.Length;
SetCurrentValue(MyPropertyProperty, TrueValue);
var x = BindingOperations.GetBindingExpression(this, MyPropertyProperty);
if (x != null)
{
x.UpdateSource();
}
};
}
public int? TrueValue { get; set; }
public int? MyProperty
{
get { return (int?)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int?), typeof(TextBoxEx), new PropertyMetadata(null, PropertyChangedCallback));
private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue == null)
{
d.SetCurrentValue(MyPropertyProperty, (d as TextBoxEx).TrueValue);
}
}
}
这是我正在绑定的 DataContext:
public class VM : INotifyPropertyChanged
{
private int? _Bar = null;
public int? Bar
{
get { return _Bar; }
set
{
_Bar = value;
OnPropertyChanged("Bar");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我的绑定看起来像这样:
<local:TextBoxEx MyProperty="{Binding Bar, UpdateSourceTrigger=PropertyChanged}"/>
记住:我需要双向绑定,所以 OneWayToSource 对我没用。
你知道我漏掉了什么吗?