WPF MVVM应用程序中的初始屏幕
我有一个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环境中标签中的默认消息。另外由于某种原因,当我从视图模型传递一个作为参数的自定义消息时,它不会显示在标签中。我究竟做错了什么?
您没有为您的网格设置的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>
这是通过做你说什么,但我也必须修改: typeof(System.Window.Controls.Label)typeof(SplashScreen) – user1624552
如果你想留在MVVM,你可以只添加一个DependencyProperty到您的窗口和标签绑定到它。 –
这里不需要MVVM或私有属性,只需在构造函数中将标签文本直接设置为传递字符串即可。尽管你当然应该确保你没有在主应用程序中从你的视图模型中实例化这个窗口,因为它会打破整个概念。 – Evk
@Evk是的,我将实例化我的视图模型中的初始屏幕,并在实例化它时传递自定义字符串。那么更好地使用dependencyProperty呢?正如ManfredRadlwimmer所说的。 – user1624552