内容控制中的用户控件

本文关键字:控件 用户 内容控制 | 更新日期: 2023-09-27 17:56:05

是否可以将一些UserControl插入到ContentControl中?

但我需要动态决定我需要插入哪个用户控件(如使用数据模板选择器)。

内容控制中的用户控件

这是可能的。你需要有一个ContentControl让我们像这样说:

<ContentControl Name="ContentMain"  Width="Auto" Opacity="1" Background="Transparent" ></ContentControl>

然后你需要像下面这样有不同的UserControl

<UserControl x:Class="MyNamespace.UserControl1"
         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" >
<Grid Margin="5,5,5,10" >
    <Label Name="labelContentOne" VerticalAlignment="Top" FontStretch="Expanded" />
</Grid>

<UserControl x:Class="MyNamespace.UserControl2"
         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" >
<Grid Margin="5,5,5,10" >
    <Label Name="labelContentTwo" VerticalAlignment="Top" FontStretch="Expanded" />
</Grid>

如果要动态更改它们,只需以编程方式更改ContentMain ContentControl 的内容:

// Initialize the content
UserControl1 u1 = new UserControl1();
ContentMain.Content = u1;

// Let's say it changes on a button click (for example)
private void ButtonChangeContent_Click(object sender, RoutedEventArgs e)
{
    UserControl2 u2 = new UserControl2();
    ContentMain.Content = u2;
}

多或少就是这个想法... ;)

是的,您可以将任何对象放置在 ContentControl.Content 中,但是根据确定您想要的用户控件的内容,有多种方法可以实现此目的。

我个人最喜欢的是使用根据某些条件确定ContentControl.ContentTemplateDataTrigger

下面是一个基于组合框的选定值ContentControl.Content的示例:

<DataTemplate DataType="{x:Type DefaultTemplate}">
    <TextBlock Text="Nothing Selected" />
</DataTemplate>
<DataTemplate DataType="{x:Type TemplateA}">
    <localControls:UserControlA />
</DataTemplate>
<DataTemplate DataType="{x:Type TemplateB}">
    <localControls:UserControlB />
</DataTemplate>
<Style TargetType="{x:Type ContentControl}" x:Key="MyContentControlStyle">
    <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedValue}" Value="A">
            <Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" />
        </DataTrigger>
        <DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedValue}" Value="B">
            <Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" />
        </DataTrigger>
    </Style.Triggers>
</Style>