使用 DataContext 显示新的 Window

Show new Window with DataContext

我只想在单独的 window 中显示我的 UserControl,例如通过调用

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

如何存档?我尝试了以下方法:

在App.xaml中设置DataTemplate:

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

在代码隐藏中调用它:

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

窗口处理程序class:

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

确实显示了 window,但它是空的。为什么是空的?我还在 UserControl 的代码隐藏中设置了 DataContext

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

Window 默认模板化为显示 Window.Content 而不是 Window.DataContext。所以你应该分配任何你想显示的内容:

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

此外,正如其他人指出的那样,您应该删除此行:

DataContext = this;

来自您的 SchoolUserControl,否则您将无法从控件中访问模板化视图模型。由于 SchoolUserControlDataTemplate 的一部分,模板化视图模型将自动从 SchoolUserControl.DataContext.

获得