简体   繁体   English

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

[英]Best practice for using BindingExpression in WPF?

I have some UI elements that do some UI-specific work in code behind then update a binding in the data context. 我有一些UI元素,它们在代码后面做一些特定于UI的工作,然后在数据上下文中更新绑定。

WPF Elements: 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" />

Code behind: 后面的代码:

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

The property in my ViewModel looks like: 我的ViewModel中的属性如下所示:

public string PartNumber{
    get { return _partNumber; }
    set { _partNumber = value; OnPropertyChanged("PartNumber"); }
}

I'm using explicit binding and only updating the source if things check out, otherwise I'm just reverting to the original binding. 我正在使用显式绑定,并且仅在事情签出时才更新源,否则,我将恢复为原始绑定。

The question is, is this the best way to work with the binding explicitly? 问题是,这是显式使用绑定的最佳方法吗? If I'm getting the BindingExpression of 100 elements of varying types, do I need to do it by hand each time? 如果要获取100个不同类型的元素的BindingExpression,是否需要每次手动处理? Would I be able to do it in a more reusable way? 我能以更可重用的方式做到这一点吗?

If I understand correctly, you are willing to check the value entered in the TextBox and update the binding only if it is valid, right? 如果我理解正确,那么您愿意检查在TextBox输入的值并仅在绑定有效时更新绑定,对吗?

Well luckily, WPF has a built-in error handling process which is way cleaner that what you did there. 幸运的是,WPF具有内置的错误处理过程,该过程比您在其中所做的更干净。 You should read something about IDataErrorInfo 您应该阅读有关IDataErrorInfo

This article is pretty clear about how to use it 本文很清楚如何使用它

As an example in your case, you'd have something like this: 以您的情况为例,您将具有以下内容:

WPF Elements: 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" />

In your ViewModel , you should have this: 在您的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;
            }
        }

This should do the trick for you: if the string "Not valid!" 这应该为您解决问题:如果字符串“无效!” is returned, the TextBox will be displayed with a red border and the Binding won't be updated 返回, TextBox将显示为红色边框,并且Binding不会更新

Why are you forced to use explicit binding? 为什么要强制使用显式绑定? Why not do the validation in your ViewModel and then fire off an OnPropertyChanged("BindingParameter") only if you need an update? 为什么不在您的ViewModel中进行验证,然后仅在需要更新时才触发OnPropertyChanged(“ BindingParameter”)?

Something like this (in VB): 像这样(在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