我在MVVM中相对较新。我可以知道这是一种可以在用户控件中获取元素并将其分别绑定到ContentTemplate
中的方法吗?我起草了如下示例代码。
我有一个由RedStack
,GreenStack
,BlueStack
组成的用户控件。我的目标是如果条件A然后在RedStack
中显示BlueStack
和ContentTemplate
,否则在ContentTemplate
彩色用户控件:
<UserControl x:Class="MapDisplay.ColorView"
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">
<StackPanel>
<StackPanel x:Name="RedStack">
<Rectangle Fill="Red" Width="100" Height="100"/>
</StackPanel>
<StackPanel x:Name="GreenStack" >
<Rectangle Fill="Green" Width="100" Height="100"/>
</StackPanel>
<StackPanel x:Name="BlueStack" >
<Rectangle Fill="Blue" Width="100" Height="100"/>
</StackPanel>
</StackPanel>
主要用户控件:
<UserControl x:Class="WpfApplication.UserControl"
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"
xmlns:custom="clr-namespace:MapDisplay;assembly=MapDisplay"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
mc:Ignorable="d" >
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<DataTemplate DataType="{x:Type custom:ColorController}">
<custom:ColorView/>
</DataTemplate>
<DataTemplate x:Key="ColorDisplay">
<Controls:MetroAnimatedSingleRowTabControl ItemsSource="{Binding Colors}" />
</DataTemplate>
<ControlTemplate x:Key="SplitColorDisplay">
<StackPanel>
<ContentControl Content="{Binding}"
ContentTemplate="{StaticResource ColorDisplay.Colors.RedStack?}" />
<ContentControl Content="{Binding}"
ContentTemplate="{StaticResource ColorDisplay.Colors.BlueStack?}" />
</StackPanel>
</ControlTemplate>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Border>
<ContentControl DockPanel.Dock="Top" Content="{Binding}">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="ContentTemplate" Value="{StaticResource ColorDisplay}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsSplitColor}" Value="True">
<Setter Property="Template" Value="{StaticResource SplitColorDisplay}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</Border>
</UserControl>