我有一个愚蠢的问题,我敢肯定会遇到很多人。但是,我无法找到令人满意的解决方案。
考虑简单的项目(请参见下面的代码)。当我在字段中键入文本,然后单击[x]
以关闭窗口时,更改将VeryImportantProperty
在窗口的Closing事件之后发生。结果,窗口关闭而不要求保存更改。
是否有已知的解决方法或更好的编程技术?我发现的唯一建议是,通过启动优先级较低的子同步线程(不执行任何操作)来延迟关闭处理程序。但是,这并没有太大作用,因为绑定和关闭事件处理程序在同一线程中运行。
C#:
namespace CloseRequestTestProject {
public class MyViewModel : INotifyPropertyChanged {
public MyViewModel() { _isDirty = false; _veryImportantProperty = "Change me!"; }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null) {
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
private bool _isDirty;
private string _veryImportantProperty;
public string VeryImportantProperty {
get { return _veryImportantProperty; }
set {
if (value != _veryImportantProperty) {
Trace.TraceWarning("Binding event!");
Trace.TraceWarning("ThreadId is " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
_isDirty = true;
_veryImportantProperty = value;
OnPropertyChanged("VeryImportantProperty");
}
}
}
public void viewIsClosing(object sender, CancelEventArgs e) {
Trace.TraceWarning("View is closing");
Trace.TraceWarning("ThreadId is " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
if (_isDirty) {
switch (MessageBox.Show("VeryImportantProperty has changed. Save changes?", "Question", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning)) {
case MessageBoxResult.Yes: ; break;
case MessageBoxResult.No: ; break;
default: e.Cancel = true; break;
}
}
}
}
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
MyViewModel vm = new MyViewModel();
DataContext = vm;
Closing += vm.viewIsClosing;
}
}
}
XAML:
<Window x:Class="CloseRequestTestProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<WrapPanel>
<TextBlock Text="Very Important Property" VerticalAlignment="Top" Margin="10"/>
<TextBox Text="{Binding VeryImportantProperty}" VerticalAlignment="Top" Margin="10" MinWidth="200"/>
</WrapPanel>
</Grid>
</Window>
UpdateSourceTrigger=PropertyChanged
在绑定中添加A可能是一个不错的开始!
IsDirty
财产将true
在ViewIsClosing
被致电时本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句