Wpf 如何在主窗口中显示用户控件?
我正在尝试构建一个小型MVVM测试应用程序,但无法真正理解如何在主窗口中显示我的用户控件 我的解决方案资源管理器: 我有一本资源字典:Wpf 如何在主窗口中显示用户控件?,wpf,binding,user-controls,Wpf,Binding,User Controls,我正在尝试构建一个小型MVVM测试应用程序,但无法真正理解如何在主窗口中显示我的用户控件 我的解决方案资源管理器: 我有一本资源字典: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespa
<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>
构建VS2010解决方案,然后转到主窗口的XAML 在左边,有一个带有按钮“工具箱”的工具栏 打开它,它包含您可以添加到UI中的所有可能的WPF控件
您的UserControl应该出现在列表的顶部(在一个可能命名为“MVVM控件”的类别中),只需将其拖放到您的UI:)最明显、最简单的方法是添加
ContentControl
元素:
<Grid>
<ContentControl x:Name="mainContentControl" />
</Grid>
但我更愿意使用另一种没有数据模板的方式:
<Grid>
<vw:View x:Name="mainView"/>
</Grid>
this.mainView.DataContext = new ViewModel.ViewModel();
this.mainView.DataContext=新的ViewModel.ViewModel();
什么意思,工具箱没有显示,或者用户控件没有显示在列表中?很好的提示,这节省了我的时间,因为我通常通过名称空间添加用户控件!显然VS2013(Premium)已经开始了,搜索工具箱不会产生用户控制或mvvm结果。
<Grid>
<vw:View x:Name="mainView"/>
</Grid>
this.mainView.DataContext = new ViewModel.ViewModel();