2011-03-29 59 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

相關問題