我有一个基于TextBox控件的WPF控件:
public class DecimalTextBox : TextBox我有一个绑定到的依赖项属性,它管理数值,并负责设置Text属性:
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);
}
}当将一个值输入到textbox本身时(它更新基础值等.),这是很好的。但是,当更改NumericValue的绑定属性时,尽管更新了NumericValue DP,但NumericValue属性仍未更新。在我所做的测试中,原因似乎是在更新绑定值时没有调用上面的set方法。所讨论的绑定如下:
<myControls:DecimalTextBox NumericValue="{Binding Path=MyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>有人能告诉我为什么这位地产策划人没有开火,或者有更好的方法来解决这个问题吗?
发布于 2017-07-10 11:17:16
正如在自定义依赖属性和XAML加载和依赖属性中所解释的,在依赖项属性的CLR包装器中,除了GetValue和SetValue之外,不应该调用其他任何东西:
由于属性设置的XAML处理器行为的当前WPF实现完全绕过包装器,因此不应将任何附加逻辑放入自定义依赖项属性的包装器的集定义中。如果将此逻辑放入set定义中,则当属性在XAML中而不是在代码中设置时,将不会执行该逻辑。
为了得到有关值更改的通知,您必须向依赖项属性元数据注册一个PropertyChangedCallback。
public static readonly DependencyProperty NumericValueProperty =
DependencyProperty.Register(
"NumericValue", typeof(decimal), typeof(DecimalTextBox),
new PropertyMetadata(NumericValuePropertyChanged));
public decimal NumericValue
{
get { return (decimal)GetValue(NumericValueProperty); }
set { SetValue(NumericValueProperty, value); }
}
private static void NumericValuePropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var textBox = (DecimalTextBox)obj;
textBox.Text = e.NewValue.ToString();
}https://stackoverflow.com/questions/45010390
复制相似问题