C# WPF通过MVVM禁用窗口关闭按钮
我试图通过MVVM禁用窗口上的关闭按钮 我意识到您可以在视图(窗口)CS代码中通过声明C# WPF通过MVVM禁用窗口关闭按钮,c#,wpf,mvvm,C#,Wpf,Mvvm,我试图通过MVVM禁用窗口上的关闭按钮 我意识到您可以在视图(窗口)CS代码中通过声明 public Window() { InitializeComponent(); this.Closing += new System.ComponentModel.CancelEventHandler(Window_Closing); } void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
public Window()
{
InitializeComponent();
this.Closing += new System.ComponentModel.CancelEventHandler(Window_Closing);
}
void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
然而,我想保持它的一致性,并试图做到这一点是MVVM
谢谢,您可以使用Windows的ResizeMode,也可以使用Windows API使用Windows API mentioend,这是一个奇怪的需求。如果你有一个关闭按钮,为什么你要禁用它的功能。但您可以通过mvvm实现它,如下所示: 添加两个参考: -Microsoft.Expression.Interactions.dll -System.Windows.Interactivity.dll 添加两个xmln:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
创建触发器到窗口:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:control="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
Title="MainWindow" Height="350" Width="525">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<ei:CallMethodAction TargetObject="{Binding}" MethodName="WindowsClosing"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid >
</Grid>
</Window>
使用ViewModel中的变量更改关闭方法
void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = (this.DataContext as MyViewModel).ProcessWorking;
}
在ViewModel(MyViewModel
)中添加属性ProcessWorking
:
public Boolean ProcessWorking
{
get { return this.processWorking; }
}
在后台线程的方法中,只需修改processWorking
private Boolean processWorking;
private void MyBackgroundThread()
{
this.processWorking = true;
// do your process
this.processWorking = false;
}
如果要在UI的某个地方显示后台进程的状态,可以在修改此.processWorking时添加
RaisePropertyChange()
。为什么这样做?你有一个关闭按钮,你禁用了它的功能,那么,为什么不把它隐藏起来呢?因为我正在触发一个后台线程,所以我需要阻止用户在线程发生时触发事件,一旦线程完成,当然我会启用它。这看起来不错。今天的某个时候,我将尝试并标记为答案。这是因为我正在触发一个后台线程,所以我需要阻止用户在线程发生时触发事件,一旦线程完成,当然我会启用它back@user3428422我现在明白了!顺便说一句,互动至少需要.net4.0。
private Boolean processWorking;
private void MyBackgroundThread()
{
this.processWorking = true;
// do your process
this.processWorking = false;
}