代码之家  ›  专栏  ›  技术社区  ›  bwoogie

如何取消数据绑定更改?

  •  0
  • bwoogie  · 技术社区  · 6 年前

    我有一个包含对象的列表视图。当用户选择要编辑的项目时,将打开一个表单,用户可以在其中进行更改。当前,当用户在进行更改后关闭表单时,列表视图中的原始对象将被更新,即使他在不单击“保存”的情况下关闭了表单。当用户要取消更改时,如何阻止数据绑定?


    <!--xaml-->
    <TextBox x:Name="tbFirstName" Text="{Binding Path=MyObject.first_name}" />
    <TextBox x:Name="tbLastName" Text="{Binding Path=MyObject.last_name}"  />
    

    public class MyObject {
         public string FirstName {get; set;}
         public string LastName {get; set;}
    }
    
    List<MyObject> listOfObjects = new List<MyObject>(); 
    

    //user selects what he wants to edit from a ListView and clicks the Edit button
    //the object is passed to a new form where he can make the desired changes.
    //the editing form is automatically populated with the object thanks to data binding! this is good! :)
    

    //Edit Button Clicked:
    EditorForm ef = new EditorForm(listOfObjects[listview.SelectedIndex]);
    ef.ShowDialog();
    

    private MyObject myObject;
    
    public EditorForm(MyObject obj) {
        InitializeComponent();
        myObject = obj;
        DataContext = this;
    }        
    

    //user makes changes to FirstName
    //user decides to cancel changes by closing form.
    //>>> the object is still updated thanks to data-binding. this is bad. :(
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Nick    6 年前

    将editorform中的绑定更改为使用updateSourceTrigger=explicit。这不会使属性在您更改UI上的值时自动更新。相反,您必须通过编程触发绑定来更新属性。

    <!--xaml-->
    <TextBox x:Name="tbFirstName" Text="{Binding Path=MyObject.first_name, UpdateSourceTrigger=Explicit}" />
    <TextBox x:Name="tbLastName" Text="{Binding Path=MyObject.last_name, UpdateSourceTrigger=Explicit}"  />
    

    单击“保存”按钮时,需要从控件中获取绑定并触发更新:

    var firstNameBinding = tbFirstName.GetBindingExpression(TextBox.TextProperty);
    firstNameBinding.UpdateSource();
    var lastNameBinding = tbLastName.GetBindingExpression(TextBox.TextProperty);
    lastNameBinding.UpdateSource();