【发布时间】:2016-01-03 06:03:09
【问题描述】:
我有一个自定义文本框,它有一个名为 valueProperty 的依赖属性,类型为双空。我的问题是该属性绑定到模型上的双打可空值和无可空值,当我尝试放置空值并且绑定值不可为空时,这显然失败,显示红色矩形。我想检测绑定失败并在发生这种情况时分配一个 0。所以我的问题是:有没有办法检测绑定失败?
我知道我可以使用 2 个不同的 customTextbox 来修复它,用于 nullables 和 no nullables,以及其他方式,只是想知道是否有办法检查绑定是否成功。提前致谢。
编辑>>>>>
型号:
private double _Temperature;
public double Temperature
{
get { return _Temperature; }
set { SetProperty(ref this._Temperature, value); }
}
private double? _Density;
public double? Density
{
get { return _Density; }
set { SetProperty(ref this._Density, value); }
}
视图(简化):
<local:customTextBox Value="{Binding Temperature}"/>
<local:customTextBox Value="{Binding Density}"/>
customTextBox 依赖属性:
public static readonly DependencyProperty valueProperty =
DependencyProperty.RegisterAttached(
"Value",
typeof(double?),
typeof(customTextBox),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnValuePropertyChanged)
);
private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
customTextBox ctb = d as customTextBox;
ntb.Value = (double?)e.NewValue;
//Here I can check the binding fail.
}
使用解决方案编辑 >>>>>
我的问题有不同的解决方案,我会列举它们:
@blindmeis 解决方案。这是最简单的一种,但效力较低:
<local:customTextBox Value="{Binding Temperature, TargeNullValue=0}"/>
@Gary H 解决方案。这是我选择的解决方案,因为它准确地回答了我的要求,并且更容易在我当前的应用程序中实现:
private static void OnValuePropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
customTextBox ctb = d as customTextBox;
ntb.Value = (double?)e.NewValue;
if (Validation.GetHasError(d))
{
//The binding have failed
}
}
@tomab 解决方案。我认为使用转换器是一个很好的解决方案(也许更好),但由于其他依赖属性,我仍然需要保留 customTextBox 类,并且我需要重构这么多代码。在以后的实施中,我会牢记这种方式。
感谢大家的帮助。
【问题讨论】:
-
您是否创建了专门用于显示
double值的自定义TextBox? -
是的,还有其他一些实用程序,比如一些依赖属性,可以轻松进行单位转换(幅度、单位等)。
-
您描述的场景:转换、
nullables等最好使用转换器 (IValueConverter) 处理。为他们使用 Dep Properties 是一种开销。使用转换器,您将能够处理非常简单的“可空”和其他转换问题。 -
Null 有时是一个有效值,如果不是,我就不会有可为空的双精度数。如果绑定的属性在 viewModel 上,我将如何从视图中区分何时转换和何时不转换?
-
绑定中的 TargetNullValue=0 怎么样?
标签: c# wpf mvvm binding textbox