WPF ContentControl 未显示用户控件(应由 DataContext 绑定)
WPF ContentControl not showing user control (which should be bound by DataContext)
我有一个包含 ContentControl 的 UserControl,ContentControl 又应该根据设置为 DataContext 的视图模型呈现一个 UserControl。
XAML:
<UserControl.Resources>
<DataTemplate DataType="{x:Type pcViewModels:SystemPCViewModel}">
<controls:SystemPCControl />
</DataTemplate>
<DataTemplate DataType="{x:Type pcViewModels:ChipPCViewModel}">
<controls:ChipPCControl />
</DataTemplate>
<!-- Left out other definition, I guess you get the point -->
</UserControl.Resources>
<Grid Background="Aqua">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollViewer Background="Blue">
<ContentControl DataContext="{Binding CurrentContent}"/>
</ScrollViewer>
<StackPanel
Grid.Row="1"
Orientation="Horizontal" FlowDirection="RightToLeft">
<Button
Width="150" Height="50"
Content="Configure"
VerticalAlignment="Center"
Command="{Binding CurrentContent.ConfigureCommand}" />
</StackPanel>
</Grid>
我让 Grid 和 ScrollViewer 的背景变得丑陋可见,只是为了确保它可见。所以这一切都是可见的,我可以看到视图模型与 DataContext 一样(按钮也可以正常工作)。
我以前用过一个 ContentControl,据我所知完全是这样。我做错了什么?
您必须设置 Content property of your ContentControl。您可以执行以下任一操作:
<ContentControl DataContext="{Binding CurrentContent}" Content="{Binding}" />
或
<ContentControl Content="{Binding CurrentContent}" />
我有一个包含 ContentControl 的 UserControl,ContentControl 又应该根据设置为 DataContext 的视图模型呈现一个 UserControl。
XAML:
<UserControl.Resources>
<DataTemplate DataType="{x:Type pcViewModels:SystemPCViewModel}">
<controls:SystemPCControl />
</DataTemplate>
<DataTemplate DataType="{x:Type pcViewModels:ChipPCViewModel}">
<controls:ChipPCControl />
</DataTemplate>
<!-- Left out other definition, I guess you get the point -->
</UserControl.Resources>
<Grid Background="Aqua">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollViewer Background="Blue">
<ContentControl DataContext="{Binding CurrentContent}"/>
</ScrollViewer>
<StackPanel
Grid.Row="1"
Orientation="Horizontal" FlowDirection="RightToLeft">
<Button
Width="150" Height="50"
Content="Configure"
VerticalAlignment="Center"
Command="{Binding CurrentContent.ConfigureCommand}" />
</StackPanel>
</Grid>
我让 Grid 和 ScrollViewer 的背景变得丑陋可见,只是为了确保它可见。所以这一切都是可见的,我可以看到视图模型与 DataContext 一样(按钮也可以正常工作)。
我以前用过一个 ContentControl,据我所知完全是这样。我做错了什么?
您必须设置 Content property of your ContentControl。您可以执行以下任一操作:
<ContentControl DataContext="{Binding CurrentContent}" Content="{Binding}" />
或
<ContentControl Content="{Binding CurrentContent}" />