2017-10-11 89 views
0

我有一個MVVM WPF應用程序,從中顯示啓動屏幕,同時執行一些長期任務。WPF MVVM應用程序中的初始屏幕

這個啓動畫面是一個典型的WPF窗口,非常簡單,它只有一個標籤來顯示自定義文本,如「加載...」和微調。

其代碼隱藏僅具有構造函數,其中只執行InitializeComponent和and事件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環境中標籤中的默認消息。另外由於某種原因,當我從視圖模型傳遞一個作爲參數的自定義消息時,它不會顯示在標籤中。我究竟做錯了什麼?

+1

如果你想留在MVVM,你可以只添加一個DependencyProperty到您的窗口和標籤綁定到它。 –

+2

這裏不需要MVVM或私有屬性,只需在構造函數中將標籤文本直接設置爲傳遞字符串即可。儘管你當然應該確保你沒有在主應用程序中從你的視圖模型中實例化這個窗口,因爲它會打破整個概念。 – Evk

+0

@Evk是的,我將實例化我的視圖模型中的初始屏幕,並在實例化它時傳遞自定義字符串。那麼更好地使用dependencyProperty呢?正如ManfredRadlwimmer所說的。 – user1624552

回答

2

您沒有爲您的網格設置的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> 
+0

這是通過做你說什麼,但我也必須修改: typeof(System.Window.Controls.Label)typeof(SplashScreen) – user1624552