WPF将网格传递给UserControl

时间:2019-03-15 14:58:54

标签: c# wpf

我目前正在开发.NET Framework 4.7.1 WPF应用程序。我是WPF的新手,我想将按钮传递给UserControl:

<!-- UserControl Start -->
<Grid Name="MyGridFrame">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

   <!-- Column1 Start-->
    <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden">
       <!-- Some content -->
    </ScrollViewer>
    <!-- Column1 End-->

    <!-- Column2 Start-->
      <!-- Here I would like to display my Button from outside -->
    <!-- Column2 End-->
</Grid>

然后,我想像这样使用MyGridFrame组件:

<local:MyGridFrame>
   <Button x:Name = "button" Content = "Click Me"/>  
</local:MyGridFrame>

我想使用UserControl来“构架”按钮组件。不幸的是,我不知道该怎么做。

您是否知道如何将按钮组件传递给MyGridFrame组件?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以为UserControl定义一个模板。添加<ContentPresenter />元素作为要插入的元素的占位符:

<UserControl x:Class="WpfApp1.MyGridFrame"
             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="450" d:DesignWidth="800">
    <UserControl.Template>
        <ControlTemplate TargetType="UserControl">
            <Grid Name="MyGridFrame">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>

                <!-- Column1 Start-->
                <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden">
                    <!-- Some content -->
                </ScrollViewer>
                <!-- Column1 End-->

                <!-- Column2 Start-->
                <ContentPresenter />
                <!-- Column2 End-->
            </Grid>
        </ControlTemplate>
    </UserControl.Template>
</UserControl>

...并像这样添加Button

<local:MyGridFrame>
    <Button Content = "Click Me"/>
</local:MyGridFrame>