ContentControl的精彩使用
先看效果
在WPF中ContentControl的Content属性是object,预示着它可以绑定任何类型,不管是View还是ViewModel都可以。
我们先看正确的代码
<Window.Resources>
<DataTemplate DataType="{x:Type viewModel:UniformGridViewModel}">
<view:UniformGridView />
</DataTemplate>
<viewModel:UniformGridViewModel x:Key="UniformGridViewModel" />
<view:UniformGridView x:Key="UniformGridView" />
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<ContentControl Grid.Row="0" Content="{StaticResource UniformGridView}"/>
<ContentControl Grid.Row="1" Content="{StaticResource UniformGridViewModel}"/>
<ContentControl Grid.Row="2" Content="{Binding UniformGridView}" />
<ContentControl Grid.Row="3" Content="{Binding UniformGridViewModel}" />
</Grid>
public class MainWindowViewModel : BindableBase
{
private UniformGridViewModel _uniformGridViewModel=new UniformGridViewModel();
public UniformGridViewModel UniformGridViewModel
{
get => _uniformGridViewModel;
set => SetProperty(ref _uniformGridViewModel, value);
}
private UniformGridView _uniformGridView=new UniformGridView();
public UniformGridView UniformGridView
{
get => _uniformGridView;
set => SetProperty(ref _uniformGridView, value);
}
}
<UserControl
x:Class="DataContext另类绑定.Views.UniformGridView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:DataContext另类绑定.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:prism="http://prismlibrary.com/"
d:DesignHeight="450"
d:DesignWidth="800"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d">
<Grid>
<TextBlock Text="{Binding Name}" />
</Grid>
</UserControl>
public class UniformGridViewModel:BindableBase
{
private string _name;
public string Name
{
get => _name;
set => SetProperty(ref _name, value);
}
public UniformGridViewModel()
{
Name = "Hello";
}
}
可以看到我们使用了Prism框架,对UniformGridView使用了prism:ViewModelLocator.AutoWireViewModel="True"
按理来说,应该不用多此一举写
<DataTemplate DataType="{x:Type viewModel:UniformGridViewModel}">
<view:UniformGridView />
</DataTemplate>
如果我们去掉会怎样
此时,只有
<ContentControl Grid.Row="0" Content="{StaticResource UniformGridView}"/>
<ContentControl Grid.Row="2" Content="{Binding UniformGridView}" />
是起作用的,
这是因为去掉DataTemplate后,只有直接使用StaticResource和Binding到UserControl的ContentControl显示正常,而Binding到ViewModel的ContentControl没有显示预期的UserControl。这是因为WPF不知道如何将ViewModel转换为UserControl。