【问题标题】:How to inherit WPF UserControl with placeholder?如何使用占位符继承 WPF UserControl?
【发布时间】:2019-02-15 00:17:33
【问题描述】:

我正在尝试实现以下目标,但我不确定这在 WPF 中是否可行,以及我应该寻找什么。 我想有一个基础UserControl,它将在控件的某处具有公共部分和一个基于子的部分,对于每个使用基础UserControl 的控件来说,这将是不同的。 我做了一张简单的图片来说明这一点:

所以每个继承基UserControlUserControl 都应该在子内容中定义控件。这可能吗?

【问题讨论】:

  • 您可以创建一个样式来替换 UserControl 的模板,而不是从 UserControl 继承,例如这个:stackoverflow.com/a/10427420/1136211
  • 寻找一个内容展示器,它将允许您在控件中显示 xaml 元素 例如,一个按钮的作用正是您可以将自定义 xaml 放在按钮内,而按钮保持原样
  • 这不仅仅是一个包含内容控件的用户控件,是否有特殊原因?或者一个带有模板的内容控件,可以在您的内容周围添加所有内容。用户控件封装了什么行为?

标签: c# wpf


【解决方案1】:

您可以在某处定义一个通用的ControlTemplate,例如在您的App.xaml 文件中:

<Application.Resources>
    <ResourceDictionary>
        <ControlTemplate x:Key="CommonTemplate" TargetType="UserControl">
            <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" 
                    Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="Label" />
                    <TextBox Grid.Column="1" />

                    <TextBlock Grid.Row="1" Text="Label" />
                    <TextBox Grid.Row="1" Grid.Column="1" />

                    <ContentPresenter Grid.Row="2" Grid.ColumnSpan="2" 
                                        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                        SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>

                    <TextBlock Grid.Row="3" Text="Label" />
                    <TextBox Grid.Row="3" Grid.Column="1" />
                </Grid>
            </Border>
        </ControlTemplate>
    </ResourceDictionary>
</Application.Resources>

然后您可以将此模板应用到您的UserControlsUserControlContent 最终会出现在模板中 ContentPresenter 所在的位置,例如:

<UserControl Template="{StaticResource CommonTemplate}">
    <TextBlock>child content....</TextBlock>
</UserControl>

【讨论】:

  • 谢谢,这看起来像我要找的。还有一个问题,我可以有 2 个不同的 ContentPresenters 吗?如果可以的话,我如何定义用户控件的每个部分的位置?
  • 没有。 UserControl 只有一个 Content 属性。
猜你喜欢
  • 2010-10-27
  • 1970-01-01
  • 2010-09-21
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
相关资源
最近更新 更多