2014-11-23 81 views
0

我有一些XAML绑定到视图模型中的属性,但我不希望它们更新,直到用户单击保存按钮。看过MSDN后,看起来我可以使用BindingGroup.UpdateSources()。但是我不知道如何获取我的XAML的容器元素,以便我可以同时更新绑定的属性。我的代码背后需要什么?按钮单击更新绑定

这是我的XAML:

<DockPanel VerticalAlignment="Stretch" Height="Auto"> 
    <Border DockPanel.Dock="Top" BorderBrush="Black" BorderThickness="2"> 
     <Grid> 
      <Grid.RowDefinitions> 
       <RowDefinition Height="Auto" /> 
       <RowDefinition Height="Auto" />    
      </Grid.RowDefinitions> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="Auto" /> 
       <ColumnDefinition Width="Auto" />  
      </Grid.ColumnDefinitions> 

      <Grid.BindingGroup> 
       <BindingGroup Name="myBindingGroup1"> 
       </BindingGroup> 
      </Grid.BindingGroup>     

      <TextBlock Grid.Column="0" Grid.Row="0" Text="Address:" /> 
      <TextBox Grid.Column="1" Grid.Row="0" Text="{Binding myObject.Address, BindingGroupName=myBindingGroup1, UpdateSourceTrigger=Explicit}" /> 

      <TextBlock Grid.Column="0" Grid.Row="1" Text="ID:" /> 
      <TextBox Grid.Column="1" Grid.Row="1" Text="{Binding myObject.ID, BindingGroupName=myBindingGroup1, UpdateSourceTrigger=Explicit}" />    
     </Grid> 
    </Border> 
    <StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" Height="35" HorizontalAlignment="Center" VerticalAlignment="Bottom"> 
     <Button Content="Save" Command="saveItem" /> 
    </StackPanel> 
</DockPanel> 
+0

你没有找到我的答案有帮助吗?你有尝试过吗? – 2014-12-24 10:00:49

+0

是的,这是我最终做的,谢谢。我已经接受你的答案。 – yellavon 2014-12-24 16:03:53

+0

很高兴帮助你;) – 2014-12-24 16:04:48

回答

1

我不知道关于绑定组,但我知道如何做到这一点的另一种方式。

让您在视图模型中绑定一个对象,就像您现在拥有它并让它在视图中发生更改时进行更新一样。在对它进行任何更改(例如创建它时)之前,请在视图模型中创建该对象的深层副本(复制实际值,而不仅仅是引用类型的引用)。

当用户按下保存按钮时,只需将更改从有界属性传播到副本,然后执行任何您需要的操作(存储在数据库中,...)。如果您对新值不满意,只需从副本中覆盖它们。

如果有界对象是来自某个模型的对象,则不要直接传播对模型的更改,请使用一些临时字段。

就像下面的例子。

public class MainViewModel : ViewModelBase 
{ 
    private PersonModel model; 
    private Person person; 

    public Person Person 
    { 
     get { return person; } 
     set { SetField(ref person, value); } // updates the field and raises OnPropertyChanged 
    } 

    public ICommand Update { get { return new RelayCommand(UpdatePerson); } } 

    private void UpdatePerson() 
    { 
     if (someCondition) 
     { 
      // restore the old values 
      Person = new Person(model.Person.FirstName, model.Person.LastName, model.Person.Age); 
     } 

     // update the model 
     model.Person = new Person(Person.FirstName, Person.LastName, Person.Age); 
    } 
}