2014-11-23 83 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); 
    } 
}