我有一些 UI 元素在后面的代码中执行一些特定于 UI 的工作,然后更新数据上下文中的绑定(bind)。
WPF 元素:
<TextBox Grid.Row="1"
Text="{Binding PartNumber, UpdateSourceTrigger=Explicit}"
Name="ui_partNumber"
FontSize="35"
VerticalContentAlignment="Center" />
<Button Grid.Column="1"
Grid.Row="1"
Content="OK"
Click="PartOKClick"
FontSize="20"
Width="150" />
后面的代码:
/// <summary>
/// Handle updating the view model with the part number
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PartOKClick(object sender, RoutedEventArgs e) {
//Get the textbox's binding expression
BindingExpression be = ui_partNumber.GetBindingExpression(TextBox.TextProperty);
if (Condition) {
//Update part number binding
be.UpdateSource();
//Animate to next state
InAnimate(ui_partGrid.Name);
OutAnimate(ui_whichPartNumber.Name);
}
else {
//Discard the text in the textbox
be.UpdateTarget();
//Animate to notification state
InAnimate(ui_invalidLocation.Name);
}
}
我的 ViewModel 中的属性如下所示:
public string PartNumber{
get { return _partNumber; }
set { _partNumber = value; OnPropertyChanged("PartNumber"); }
}
我正在使用显式绑定(bind),并且仅在检查结果时才更新源,否则我只是恢复到原始绑定(bind)。
问题是,这是明确使用绑定(bind)的最佳方式吗?如果我得到 100 个不同类型元素的 BindingExpression,是否每次都需要手动完成?我能以更可重用的方式做到这一点吗?
最佳答案
如果我理解正确,您愿意检查 TextBox
中输入的值。并且仅在绑定(bind)有效时才更新绑定(bind),对吗?
幸运的是,WPF 有一个内置的错误处理过程,它比你在那里所做的要干净得多。你应该阅读一些关于 IDataErrorInfo
的内容。
This article is pretty clear about how to use it
作为你的例子,你会有这样的事情:
WPF 元素:
<TextBox Grid.Row="1"
Text="{Binding PartNumber, ValidatesOnDataErrors=True}"
Name="ui_partNumber"
FontSize="35"
VerticalContentAlignment="Center" />
<Button Grid.Column="1"
Grid.Row="1"
Content="OK"
Click="PartOKClick"
FontSize="20"
Width="150" />
在您的
ViewModel
,你应该有这个:public string this[string columnName]
{
get
{
if (string.Equals(columnName, "PartNumber", StringComparison.OrdinalIgnoreCase) || columnName == string.Empty)
{
// Here, IDataErrorInfo is checking the property "PartNumber" bound to your TextBox
if (this.IsPartNumberValid(ui_partNumber.Text))
{
// Not valid: return any error message (string.Empty = no error, otherwise it will be seen as not valid)
return "Not valid!";
}
}
return string.Empty;
}
}
这应该为您解决问题:如果字符串“无效!”返回,
TextBox
将显示红色边框和 Binding
不会更新
关于c# - 在 WPF 中使用 BindingExpression 的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14146856/