在用户控制下放置控件

时间:2013-08-04 09:16:29

标签: c# wpf user-controls wpf-controls

我是WPF的新手,我正在创建一个用户控件,如下所示:

<UserControl x:Class="WpfApplication3.MyUserControl"
         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" 
         x:Name="MyUserControl2"
         d:DesignHeight="300" d:DesignWidth="300" Background="Coral">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="20"/>
        <RowDefinition Height="20"/>
        <RowDefinition Height="20"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Button Content="a" Grid.Row="0"/>
    <Button Content="b" Grid.Row="1"/>
    <Button Content="c" Grid.Row="2"/>
    <ContentPresenter Grid.Row="3"/>
</Grid>

当橙色区域是内容预处理器时,这将产生以下布局:

the orange area is the content presenter

在使用用户控件的主窗口中,我想将控件注入内容预处理器

<Window x:Class="WpfApplication3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication3"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <local:MyUserControl>
        <local:MyUserControl.Content>
            <Button Content="d"/>
        </local:MyUserControl.Content>
    </local:MyUserControl>
</Grid>

我希望得到以下布局:

enter image description here

但是整个用户控件被按钮d重叠。

我该如何设法?

2 个答案:

答案 0 :(得分:1)

尝试将button置于Main Window -

<Grid>
    <local:MyUserControl/>
    <Button Content="d"/>
</Grid>

OR

<Grid>
    <Grid.Resources>
       <DataTemplate x:Key="MyContent">
          <Button Content="d"/>
       </DataTemplate>
    </Grid.Resources>
    <local:MyUserControl/>
</Grid>

并在您的用户控件中

 <ContentPresenter Grid.Row="3" ContentTemplate="{DynamicResource MyContent}"/>

答案 1 :(得分:0)

我很确定这不起作用。当您将MyControl的内容设置为按钮时,您说用户控件的整个内容应该是Button。我认为您需要在用户控件上拥有一个属性,然后将contentpresenter绑定到该属性。

所以像MyUserControl.SubContent {get; set;}然后你可以将ContentPresenter绑定到那个。