繁体   English   中英

在WPF中使用BindingExpression的最佳实践?

[英]Best practice for using BindingExpression in WPF?

我有一些UI元素,它们在代码后面做一些特定于UI的工作,然后在数据上下文中更新绑定。

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"); }
}

我正在使用显式绑定,并且仅在事情签出时才更新源,否则,我将恢复为原始绑定。

问题是,这是显式使用绑定的最佳方法吗? 如果要获取100个不同类型的元素的BindingExpression,是否需要每次手动处理? 我能以更可重用的方式做到这一点吗?

如果我理解正确,那么您愿意检查在TextBox输入的值并仅在绑定有效时更新绑定,对吗?

幸运的是,WPF具有内置的错误处理过程,该过程比您在其中所做的更干净。 您应该阅读有关IDataErrorInfo

本文很清楚如何使用它

以您的情况为例,您将具有以下内容:

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不会更新

为什么要强制使用显式绑定? 为什么不在您的ViewModel中进行验证,然后仅在需要更新时才触发OnPropertyChanged(“ BindingParameter”)?

像这样(在VB中):

Property prop as Object
  Get
   return _prop
  End Get 
  Set(ByVal value As Object)
    If your_validation_check(value) then
      _prop = value
      OnPropertyChanged("prop") 'INotifyPropertyChanged
    End If
  End Set 
End Property

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM