WPF MVVM应用程序中的启动画面

时间:2017-10-11 07:54:31

标签: c# wpf mvvm inotifypropertychanged

我有一个MVVM WPF应用程序,在完成一些长任务时,我会从中显示启动画面。

这个启动画面是一个典型的WPF窗口,非常简单,它只有一个标签来显示自定义文本,例如“正在加载......”和一个微调器。

它的代码隐藏只有构造函数,它只执行InitializeComponent和事件Window_Loaded。

从我的主MVVM WPF应用程序,当我执行一个长任务时,我实例化这个窗口并显示启动画面。

现在,我想自定义启动画面中标签中显示的文字。那么最好的方法是什么?

我做的是在实例化窗口(Splash Screen)时将一个字符串(自定义消息)作为参数传递给构造函数。

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

由于这个启动画面非常简单,只是一个启发,我认为在这里应用MVVM是没有意义的,所以在代码隐藏中我创建了一个私有属性,我将其作为参数传递给构造函数。然后,我将视图中的标签绑定到这个私有属性,最后我在代码隐藏(视图)中实现了INotifyPropertyChanged。这里没有模型,模型视图。

这是正确的方法吗?或者还有其他方式吗?

我知道还有其他解决方案,例如通过添加以下内容在视图中公开标签:

x:FieldModifier="public"

然后在我实例化启动画面时访问它但我不喜欢这个解决方案,我不想在外面公开标签。

ATTEMPT#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 个答案:

答案 0 :(得分:2)

您没有为网格设置DataContext:

Traceback (most recent call last):
  File "C:/Users/.PyCharmCE2017.2/config/scratches/trtr.py", line 30, in <module>
    filewriter.writerow(["CN", "NCR", "TRDT"])  # change the column labels here
TypeError: a bytes-like object is required, not 'str'
相关问题