wpf - 如何仅覆盖自定义控件中的 ItemTemplate

标签 wpf themes styles

我想创建一个从ComboBox派生的自定义控件,但是如果我从Visual Studio模板创建自定义控件,它会创建一个默认的Style控件,我必须然后打开 MSDN 的 ComboBoxControlTemplate,然后在 generic.xaml 中再次重新创建整个 ComboBox 样式

我想要做的是,我想创建一个派生自 ComboBox 的自定义控件,并且在 generic.xaml 中我只想定义一个 ItemTemplate 而不是整个控制模板

但是如果我保留这条线

static MyComboBox()
{
    DefaultStyleKeyProperty.
         OverrideMetadata(typeof(MyComboBox), 
         new FrameworkPropertyMetadata(
             typeof(MyComboBox)));
}

然后,如果我从 generic.xaml 中删除 ControlTemplate ,我什么也看不到,但是如果我在 generic.xaml 中定义键 ItemTemplate ,我应该如何初始化我的静态构造函数以便仅反射(reflect) ItemTemplate

当然,我可以从 msdn 帮助中重新设计 xaml 主题,但有没有简单的方法可以做到这一点?

最佳答案

我最近编写了自己的自定义组合框,它仅更改控件的 ItemTemplate。组合框样式的其余部分继承自默认组合框。

在您的自定义控件构造函数中:

 static CustomComboBox()
 {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomComboBox)
                        , new FrameworkPropertyMetadata(typeof(CustomComboBox)));

 }

然后在你的 generic.xaml 中:

<Style TargetType="{x:Type local:CustomComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                **INSERT YOUR ITEM TEMPLATE HERE**
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

这里的关键是设置样式的 BasedOn 属性以引用标准组合框控件。

希望这有帮助!

关于wpf - 如何仅覆盖自定义控件中的 ItemTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1520879/

相关文章:

c# - WPF 应用程序中的 DialogResult

android - NavigationView 和半透明状态栏

themes - Visual Studio Code中不同语言的不同主题

android - 我无法获得可样式化的属性数组

c++ - Richedit Msftedit奇怪的边框

wpf - 将实体绑定(bind)到 WPF 表单 MVVM

C# WPF - 长时间点击按钮操作

wpf - 网格 SharedSizeGroup - 列在无限循环中弹跳、调整大小

ios - 根据 iOS 环境主题自动在浅色和深色之间更改 iOS 应用程序主题

xml - 列表项背景在滚动时发生变化