我正在尝试构建一个小型MVVM测试应用程序,但无法真正弄清楚如何在MainWindow中显示我的用户控件。

我的解决方案资源管理器:



我有一个资源字典:

    <ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:MVVM.ViewModel"
    xmlns:vw="clr-namespace:MVVM.View">

    <DataTemplate DataType="{x:Type vm:ViewModel}">
        <vw:View />
    </DataTemplate>

</ResourceDictionary>


我有我的看法:

<UserControl x:Class="MVVM.View.View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <DataTemplate x:Key="PersonTemplate">
            <StackPanel>
                <TextBlock Text="{Binding FirstName}" />
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>

    <ListBox ItemsSource="{Binding Path=Persons}"
             ItemTemplate="{StaticResource PersonTemplate}" />
</UserControl>


和我的MainWindow

<Window x:Class="MVVM.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:MVVM.ViewModel"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary Source="MainWindowResources.xaml" />
    </Window.Resources>

    <Grid>

    </Grid>
</Window>

最佳答案

最明显和最简单的方法是添加ContentControl元素:

<Grid>
    <ContentControl x:Name="mainContentControl" />
</Grid>


然后,将该控件的Content属性设置为您的视图模型,相应的视图将自动加载并应用:

this.mainContentControl.Content = new ViewModel.ViewModel();


但是我宁愿使用另一种没有数据模板的方式:

<Grid>
    <vw:View x:Name="mainView"/>
</Grid>
this.mainView.DataContext = new ViewModel.ViewModel();

关于wpf - 如何在MainWindow中显示用户控件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5471982/

10-12 00:28
查看更多