简体   繁体   English

显示带有DataContext的新窗口

[英]Show new Window with DataContext

I want to simply display my UserControl in a separate window, for example by calling 我只想在一个单独的窗口中显示我的UserControl ,例如通过调用

var windowHandler = new WindowHandler();
windowHandler.Show(new SchoolViewModel);

How do I archive this? 我该如何存档? I have tried the following: 我尝试了以下方法:

Set the DataTemplate in App.xaml: 在App.xaml中设置DataTemplate

<Application.Resources>
    <ResourceDictionary>
        <DataTemplate DataType="{x:Type viewModel:SchoolViewModel}">
            <view:SchoolUserControl />
        </DataTemplate>
    </ResourceDictionary>
</Application.Resources>

In code-behind call it: 在后面的代码中调用它:

private void Application_Startup(object sender, StartupEventArgs e)
{
    var windowHandler = new WindowHandler();
    windowHandler.ShowWindow(new SchoolViewModel(), 200, 200);
}

WindowHandler class: WindowHandler类:

public class WindowHandler
{
    public void ShowWindow(object dataContext, int height, int width)
    {
        Window window = new Window()
        {
            DataContext = dataContext,
            Width = width,
            Height = height
        };
        window.Show();
    }
}

It does show a window, but it's empty. 它确实显示一个窗口,但是它是空的。 Why is it empty? 为什么它是空的? I also set the DataContext in the UserControl 's code-behind: 我还在UserControl的代码后面设置了DataContext

public SchoolUserControl()
{
    InitializeComponent();
    DataContext = this;
}

Window is by default templated to show Window.Content and not Window.DataContext . 默认情况下, Window被模板化以显示Window.Content而不是Window.DataContext So you should assign whatever you want to show as content: 因此,您应该分配要显示为内容的任何内容:

public class WindowHandler
{
    public void ShowWindow(object dataContext, int height, int width)
    {
        Window window = new Window()
        {
            Content = dataContext,
            Width = width,
            Height = height
        };
        window.Show();
    }
}

Also, as others noted, you should remove this line: 另外,如其他人所述,您应该删除以下行:

DataContext = this;

from your SchoolUserControl , because otherwise you won't have access to the templated view-model from within the control. SchoolUserControl ,因为否则您将无法从控件中访问模板化视图模型。 And since SchoolUserControl is part of a DataTemplate , the templated view-model will be automatically available from SchoolUserControl.DataContext . 并且由于SchoolUserControlDataTemplate一部分,因此可以从SchoolUserControl.DataContext自动获得模板化的视图模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM