Gar*_*ghi 12 wpf binding user-controls
我正在尝试构建一个小型MVVM测试应用程序,但无法真正计算出如何在MainWindow中显示我的用户控件.
My Solution Explorer:

我有一个资源字典:
<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>
Run Code Online (Sandbox Code Playgroud)
我得到了我的观点:
<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>
Run Code Online (Sandbox Code Playgroud)
和我的主窗口
<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>
Run Code Online (Sandbox Code Playgroud)
vor*_*olf 11
最明显和最简单的方法是添加ContentControl元素:
<Grid>
<ContentControl x:Name="mainContentControl" />
</Grid>
Run Code Online (Sandbox Code Playgroud)
然后Content将此控件的属性设置为视图模型,并自动加载和应用相应的视图:
this.mainContentControl.Content = new ViewModel.ViewModel();
Run Code Online (Sandbox Code Playgroud)
但我更愿意在没有datatemplates的情况下使用另一种方法:
<Grid>
<vw:View x:Name="mainView"/>
</Grid>
this.mainView.DataContext = new ViewModel.ViewModel();
Run Code Online (Sandbox Code Playgroud)
构建您的VS2010解决方案,然后转到您的MainWindow的XAML.
在左侧,有一个工具栏,按钮"工具箱"
打开它,它包含您可以添加到UI的所有可能的WPF控件
您的UserControl应该出现在列表的顶部(在一个可能名为"MVVM Controls"的类别中),只需将其拖放到您的UI :)
| 归档时间: |
|
| 查看次数: |
28558 次 |
| 最近记录: |