簡體   English   中英

WPF通過MVVM禁用窗口關閉按鈕

[英]WPF disabling the window close button via MVVM

我正在嘗試通過MVVM禁用窗口上的關閉按鈕

我意識到您可以通過聲明在視圖(窗口)CS代碼中執行此操作

public Window()
{
    InitializeComponent();
    this.Closing += new System.ComponentModel.CancelEventHandler(Window_Closing);
}

void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    e.Cancel = true;
}

但是,我想保持一致,並嘗試使用MVVM。

謝謝

這是一個奇怪的需求。 如果您有關閉按鈕,為什么要禁用它的功能。 但是您可以使用mvvm來實現它,如下所示:

添加兩個參考:-Microsoft.Expression.Interactions.dll-System.Windows.Interactivity.dll

添加兩個xmlns:

 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,並創建關閉函數:

 public void WindowsClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
        }

您可以使用ResizeMode窗口,也可以使用窗口API使用窗口API mentioend的使用它在這里

使用ViewModel中的變量更改Closing方法。

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的某個位置顯示后台進程的狀態,則可以在修改this.processWorking時添加RaisePropertyChange()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM