Я схожу с ума с пользовательским свойством зависимости.Я уже проверил множество потоков здесь, но пока не нашел решения.То, что я хочу сделать, это заменить значение свойства, если источник предоставляет конкретное значение (ноль для данного примера).Что бы я ни пытался, значение свойства в источнике остается нулевым и никогда не обновляется.
Вот мой пользовательский элемент управления:
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}"/>
Помните: мне нужна привязка TwoWay, поэтому OneWayToSource у меня не работает.
Любая идея, чем я не являюсьздесь?