小编Sim*_*n F的帖子

WPF MVVM为什么使用ContentControl + DataTemplate Views而不是直接的XAML窗口视图?

我有一个关于WPF MVVM的问题,这让我感到沮丧.

为什么这样做:?

MainWindow.xaml:

<Window x:Class="MVVMProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <ContentControl Content="{Binding}"/>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

将您的ExampleView.xaml设置为:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vms="clr-namespace:MVVMProject.ViewModels">
    <DataTemplate DataType="{x:Type vms:ExampleVM}" >
        <Grid>
            <ActualContent/>
        </Grid>
    </DataTemplate>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)

并创建如下窗口:

public partial class App : Application {

    protected override void OnStartup(StartupEventArgs e) {

        base.OnStartup(e);

        MainWindow app = new MainWindow();
        ExampleVM context = new ExampleVM();
        app.DataContext = context;
        app.Show();
    }
}
Run Code Online (Sandbox Code Playgroud)

什么时候可以这样做:?

App.xaml :(设置启动窗口/视图)

<Application x:Class="MVVMProject.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="ExampleView.xaml">
</Application>
Run Code Online (Sandbox Code Playgroud)

ExampleView.xaml :(窗口不是ResourceDictionary)

<Window x:Class="MVVMProject.ExampleView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vms="clr-namespace:MVVMProject.ViewModels">
    >
    <Window.DataContext>
        <vms:ExampleVM />
    </Window.DataContext>

    <Grid> …
Run Code Online (Sandbox Code Playgroud)

c# architecture wpf xaml mvvm

75
推荐指数
3
解决办法
8万
查看次数

标签 统计

architecture ×1

c# ×1

mvvm ×1

wpf ×1

xaml ×1