【问题标题】:WPF Child control, style only content partWPF子控件,样式只有内容部分
【发布时间】:2017-03-07 10:12:28
【问题描述】:

我创建了一个名为“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)的样式?

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

【问题讨论】:

  • 您说自己将 TextBox 放入 Content 中,但随后您将其放入 Template 中覆盖所有内容。

标签: c# wpf xaml inheritance custom-controls


【解决方案1】:

将父控件的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?

【讨论】:

    猜你喜欢
    • 2011-08-09
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多