我有基於TextBox控件一個WPF控制更新次要屬性:管理該數值從一個DependencyProperty
public class DecimalTextBox : TextBox
我有一個綁定到一個依賴屬性,並負責設置文本屬性:
public decimal NumericValue
{
get { return (decimal)GetValue(NumericValueProperty); }
set
{
if (NumericValue != value)
{
SetValue(NumericValueProperty, value);
SetValue(TextProperty, NumericValue.ToString());
System.Diagnostics.Debug.WriteLine($"NumericValue Set to: {value}, formatted: {Text}");
}
}
}
protected override void OnTextChanged(TextChangedEventArgs e)
{
base.OnTextChanged(e);
if (decimal.TryParse(Text, out decimal num))
{
SetValue(NumericValueProperty, num);
}
}
這適用於輸入到文本框本身的值(它更新基礎值等)。但是,NumericValue的綁定屬性更改時,儘管更新NumericValue DP,Text屬性不會更新。在我所做的測試中,看起來原因是上面的set
方法在綁定值更新時不會被調用。有問題的結合看起來是這樣的:
<myControls:DecimalTextBox NumericValue="{Binding Path=MyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
任何人都可以點我在正確的方向,爲什麼這個屬性setter不點火,或是否有更好的方式來處理呢?