c# - WPF 子控件,仅样式内容部分

标签 c# wpf xaml inheritance custom-controls

我创建了一个名为“Field”的自定义控件,它继承自 ContentControl 并包含一个 Grid 和一个 label 来公开字段标签和一个 ContentPresenter 以允许根据我们要编辑的数据放置控件。

然后我创建了一个名为“TextField”的自定义控件,它继承自 Field,应该将一个 TextBox 放入内容中。

以下是 Generic.xaml 中的样式:

<Style TargetType="{x:Type controls:Field}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:Field}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <Grid x:Name="grd" Margin="3px">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="{Binding Path=LabelLength, RelativeSource={RelativeSource AncestorType=Control}}" />
                            <ColumnDefinition Width="{Binding Path=ContentLength, RelativeSource={RelativeSource AncestorType=Control}}" />
                        </Grid.ColumnDefinitions>
                        <Label Grid.Column="0" Content="{Binding Path=Label, RelativeSource={RelativeSource AncestorType=Control}}" />
                        <ContentPresenter Grid.Column="1" Content="{TemplateBinding Content}" Margin="{TemplateBinding Padding}" />
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="{x:Type controls:FieldText}" BasedOn="{StaticResource {x:Type controls:Field}}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:FieldText}">
                <TextBox Grid.Column="1" MaxLines="1" TextWrapping="NoWrap" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

根据证据,这在使用 TextField 时仅显示一个文本框。但是我怎样才能通过让控件的其余部分继承父样式来仅设置内容样式(例如本例中的 TextBox)呢?

我知道我可以为每个派生控件重写整个控件,但这违反了继承原则,不是吗?将意味着重复代码(此处重复标记),如果我更改父“字段”中的任何内容,我将不得不在每个子控件中更改它,并有出错的风险...

最佳答案

将父控件的 Content 属性设置为 TextBox 的实例,您可以根据需要设置样式:

<controls:Field Background="Gray">
    <TextBox Grid.Column="1" MaxLines="1" TextWrapping="NoWrap" />
</controls:Field>

这就是应该如何使用 ContentControl

不能只覆盖ControlTemplate的一部分:

WPF: Is there a way to override part of a ControlTemplate without redefining the whole style?

关于c# - WPF 子控件,仅样式内容部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42645440/

相关文章:

c# - 如何使用 NodeView 获得可调整大小和可排序的列?

wpf - ItemsSource + Converter + Treeview 不会更新

wpf IValueConverter 不更新 View

c# - 如何从 XAML 内部访问嵌套命名空间?

WPF:XAML 自定义命名空间

c# - 当前上下文中不存在名称 'InitializeComponent'(c#,xamarin)

c# - 如何从 C# 或 VB.Net 使用 Win32 'DwmSetIconicThumbnail'?

c# - 将异步放在不执行等待操作的 WebAPI Controller 操作上有什么好处?

c# - Linq 中的排序和唯一记录

c# - WPF:如何在 DockPanel 中拉伸(stretch)中间的 child ?