这是您的方案的一个小示例:
<Window x:Class="MementoAndLostFocus.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MementoAndLostFocus"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="10*"/>
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Text="{Binding ExampleInstance.ExampleName, UpdateSourceTrigger=LostFocus}"
BorderThickness="1"
BorderBrush="Black"
VerticalAlignment="Top"
Margin="10"/>
<Button Grid.Row="1"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Content="Save"
Command="{Binding SaveCommand}"/>
</Grid>
public class MainViewModel
{
public ExampleClass ExampleInstance { get; set; }
public ICommand SaveCommand { get; set; }
public MainViewModel()
{
ExampleInstance = new ExampleClass() { ExampleName = "Example Name" };
SaveCommand = new SaveCommand(this);
}
internal void Save()
{
//TO DO - Save item to database
Console.WriteLine(ExampleInstance.ExampleName);
}
}
public class ExampleClass : INotifyPropertyChanged
{
private string _exampleName;
public string ExampleName
{
get { return _exampleName; }
set
{
PropertyChanged(this, new PropertyChangedEventArgs(nameof(ExampleName)));
_exampleName = value;
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
public class SaveCommand : ICommand
{
private MainViewModel _vm;
public event EventHandler CanExecuteChanged;
public SaveCommand(MainViewModel vm)
{
_vm = vm;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_vm.Save();
}
}
那么这里到底发生了什么:
如您所见, 在TextBox
那里并且它UpdateSourceTrigger
被设置为LostFocus
。
当我在那里修改值并单击 Save 按钮时,我可以看到发生了什么,在 Save 方法中有一个断点并且值被更新,因为当您单击按钮时,TextBox
失去焦点。


无论如何,我想给你写这个,因为可能还有更多。
看看IEditableObject
界面:
提供对用作数据源的对象提交或回滚更改的功能。
就是这样。