WPF C# 如何通过代码创建派生样式

WPF C# How can I create derived styles by code

我想使用使用不同内容的ListBoxItems。对于 xaml 中的定义,我使用以下方法。

<Style TargetType="{x:Type ListBoxItem}" x:Key="ExampleBaseListBoxItem">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <Border>
                    <ContentPresenter  HorizontalAlignment="Stretch" VerticalAlignment="Center"      />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>   
</Style>


<Style x:Key="ExampleListBoxItem"  TargetType="{x:Type ListBoxItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <ListBoxItem Style="{DynamicResource ExampleBaseListBoxItem}">
                    <TextBox  />
                </ListBoxItem>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

这很好用,但我有两个问题。

  1. 这是在 xaml 中定义的好习惯,还是我应该使用 还有什么?

  2. 如何在样式
    时达到相同的结果 ExampleBaseListBoxItem 已经存在

请不要担心 TextBox。我正在寻找一种方法来做到这一点,示例本身仅用于演示目的。

这不是处理此类问题的常用方法。

您应该在 xaml 而不是代码中定义样式和模板。

但是

使用 Datatype= 而不是 re-templating listboxitem 来匹配视图模型类型的数据模板更为常见。

行视图模型的类型。

所以你会有(比方说)一个 TextBoxVM class、一个 DividerVM class 等

您将对象的 Observable 集合绑定到您的项目源。

将 TextBoxVM 模板化为文本框,将 dividervm 模板化为分隔线等。

我遇到的第一个例子:

<DataTemplate DataType="{x:Type local:DividerVM}">
    <local:Divider />
</DataTemplate>
<DataTemplate DataType="{x:Type local:DrawCategoryVM}">
    <Grid>
        <TextBlock FontSize="{DynamicResource BigFont}" Text="{Binding Heading}" />
    </Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type local:DrawOptionVM}">
    <Grid Height="38"
          Background="Transparent"
          >

您可以使用 basedon "inherit" 将一种样式的属性转换为另一种样式。