2011-03-29 21 views
11

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

我的解决方案资源管理:

How my solution looks like

我有资源字典:

<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> 

和我的主窗口

<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> 

回答

10

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

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

而在这之后,此调节的Content属性为您的视图模型,以及相应的视图将被加载并自动应用:

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

但我更愿意用另一种方式没有的DataTemplates:

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

构建您的VS2010解决方案,然后转到您的MainWindow的XAML。

在左边,有一个与按钮“工具箱”工具栏

打开它,它包含了所有可能的WPF控件,你可以添加到您的UI

你的用户控件应该出现在列表的顶部(在一个类别可能命名为“MVVM控件”),只需将它&拖放到你的UI :)

+0

是的,你是对的。只有我没有出现。 – 2011-03-29 12:40:31

+0

你是什么意思,它没有显示工具箱,或者usercontrol没有显示在列表中? – Damascus 2011-03-29 12:49:17

+0

它不会显示在工具箱中。 – 2011-03-29 13:08:54

相关问题