C# 单击按钮时更新绑定
我有一些绑定到视图模型中我的属性的XAML,但我不希望在用户单击“保存”按钮之前更新它们。在阅读了一些关于它的内容之后,我可以使用BindingGroup.UpdateSources()。但是,我不知道如何获取XAML的容器元素,以便同时更新绑定属性。我的代码隐藏需要什么 这是我的XAML:C# 单击按钮时更新绑定,c#,wpf,xaml,C#,Wpf,Xaml,我有一些绑定到视图模型中我的属性的XAML,但我不希望在用户单击“保存”按钮之前更新它们。在阅读了一些关于它的内容之后,我可以使用BindingGroup.UpdateSources()。但是,我不知道如何获取XAML的容器元素,以便同时更新绑定属性。我的代码隐藏需要什么 这是我的XAML: <DockPanel VerticalAlignment="Stretch" Height="Auto"> <Border DockPanel.Dock="Top" Border
<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>
我不知道绑定组,但我知道如何用另一种方式进行绑定 在视图模型中创建一个与当前对象绑定的对象,并在视图中发生更改时对其进行更新。在对其进行任何更改之前(例如,在创建对象时),请在视图模型中创建对象的深度副本(复制实际值,而不仅仅是引用类型的引用) 当用户按下“保存”按钮时,只需将更改从绑定属性传播到副本,并执行您需要对其执行的任何操作(存储在数据库中,…)。如果您对新值不满意,只需从副本中覆盖它们即可 如果有界对象是某个模型中的对象,请不要直接将更改传播到模型,而是使用一些临时字段 类似于下面的示例
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);
}
}
你不觉得我的回答有用吗?你试过了吗?是的,这就是我最后做的,谢谢。我接受了你的回答。很高兴它对你有帮助;)