簡體   English   中英

WPF MVVM應用程序中的啟動畫面

[英]Splash screen in WPF MVVM application

我有一個MVVM WPF應用程序,當完成一些漫長的任務時,我會從中顯示啟動屏幕。

此初始屏幕是典型的WPF窗口,非常簡單,它只有一個標簽來顯示自定義文本,例如“ Loading ...”和一個微調框。

其背后的代碼僅具有僅在其中執行InitializeComponent和事件Window_Loaded的構造函數。

在我的主要MVVM WPF應用程序中,當我執行一個長任務時,我將實例化此窗口並顯示啟動屏幕。

因此,現在,我要自定義初始屏幕標簽中顯示的文本。 那么最好的方法是什么?

我所做的是在實例化窗口(啟動畫面)時將字符串(自定義消息)作為參數傳遞給構造函數。

Window mySplash = new SplashScreen("Loading or whatever I want");

由於此啟動畫面非常簡單,僅是啟動畫面,我認為在此處應用MVVM沒有意義,因此在代碼背后,我創建了一個私有屬性,該屬性通過將字符串作為參數傳遞給構造函數來設置。 然后,將視圖標簽與此私有屬性綁定在一起,最后在后台代碼(視圖)中實現INotifyPropertyChanged。 這里沒有模型,沒有模型視圖。

那是正確的方法嗎? 或還有其他方法嗎?

我知道還有其他解決方案,例如通過添加以下內容在視圖中公開標簽:

x:FieldModifier="public"

然后實例化初始屏幕時訪問它,但是我不喜歡這種解決方案,我不想將標簽暴露在外面。

嘗試#1:

從我在主要MVVM WPF應用程序中的視圖模型,我執行以下操作:

Window splashScreen = new SplashScreen("Loading ..."); 

啟動畫面窗口:

<Window x:Class="My.Apps.WPF.SplashScreen"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid>
    <!-- Grid row and column definitions here -->
         <Label Grid.Row="0" Content="{Binding Path=Message}"/>  
    </Grid>
</Window>

開機畫面背后的代碼:

public partial class SplashScreen: Window
{
    public string Message
    {
        get
        {
            return (string)GetValue(MessageProperty);
        }
        set { SetValue(MessageProperty, value); }
    }
    public static readonly DependencyProperty
        MessageProperty =
        DependencyProperty.Register("Message",
        typeof(string), typeof(System.Window.Controls.Label),
        new UIPropertyMetadata("Working, wait ..."));

    public SplashScreen(string message)
    {
        InitializeComponent();

        if (!String.IsNullOrEmpty(message))
            this.Message = message;
    }

}

我已經為Label設置了默認值,如果它沒有作為參數傳遞給構造函數,它將被使用。

它不起作用,在xaml預覽中,Visual Studio IDE環境中的標簽中未顯示默認消息。 同樣由於某種原因,當我將視圖模型中的自定義消息作為參數傳遞時,該消息未顯示在標簽中。 我究竟做錯了什么?

您沒有為網格設置DataContext:

<Window x:Class="My.Apps.WPF.SplashScreen"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Name="Splash"
>

    <Grid DataContext="{Binding ElementName=Splash}">
    <!-- Grid row and column definitions here -->
         <Label Grid.Row="0" Content="{Binding Path=Message}"/>  
    </Grid>
</Window>

暫無
暫無

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

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