ContentControl中的UserControl

时间:2013-01-24 16:42:33

标签: c# wpf

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

但我需要动态决定我需要插入哪个UserControl(比如DataTemplateSelector)。

2 个答案:

答案 0 :(得分:9)

有可能。你需要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;
}

或多或少那个想法......;)

答案 1 :(得分:5)

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

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

这是一个基于ContentControl.Content基于ComboBox所选值的示例:

<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>
相关问题