简体   繁体   English

WPF 自定义控制的设置内容

[英]WPF Setting Content for Custom Control

In my WPF app I have several labels on multiple pages that all look the same but may change style during program running (all at once).在我的 WPF 应用程序中,我在多个页面上有多个标签,它们看起来都一样,但在程序运行期间可能会改变样式(一次全部)。

After much searching online, I have gone through Window.Resources templates and User Controls (neither great for styling when changes are possible during program run) and have currently settled on CustomControl.在网上搜索了很多之后,我浏览了 Window.Resources 模板和用户控件(在程序运行期间可能更改样式时,它们都不是很好的样式),目前已选择 CustomControl。 However, I can't figure out how to set its Content.但是,我不知道如何设置它的内容。 Some labels will have a wrap panel with mutiple grandchildren and some will just have text.有些标签会有一个带有多个孙子的包装面板,有些标签只有文字。 However, I cannot work it out either way.但是,无论哪种方式,我都无法解决。 This seems to be a program beyond Label.这似乎是Label之外的程序。 What am I missing?我错过了什么?

My Control (just changed to inherit from Label):我的控件(只是更改为从标签继承):

 public class MyControl : Label
    {
        static MyControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
        }
    }

No changes to Themes.Generic.xaml Themes.Generic.xaml 没有变化

My Window XAML (styling here for testing purposes):我的 Window XAML (此处为测试目的设计):

<local:MyControl Height="100">
            <TextBlock Text="hi there" FontSize="60"></TextBlock>
            <!-- More children will be needed, but lets start with one for now -->
</local:MyControl>

<local:MyControl Height="100" Content="this should exist" FontSize="50" />

How do I get that content to show up?如何让该内容显示?

Edit: Removing the DefaultStyleKeyProperty.OverrideMetadata worked.编辑:删除 DefaultStyleKeyProperty.OverrideMetadata 工作。

You should define a default template for your custom control if you're to override its DefaultStyleKeyProperty , in your Themes/Generic.xaml .如果要在Themes/Generic.xaml中覆盖其DefaultStyleKeyProperty ,则应为自定义控件定义一个默认模板。 Base it on the default template of Label :基于Label的默认模板:

<Style TargetType="{x:Type local:MyControl}" BasedOn="{StaticResource {x:Type Label}}"/>

Alternatively, you can remove the overriding of the DefaultStyleKeyProperty and leave your control like this:或者,您可以删除DefaultStyleKeyProperty的覆盖并保留您的控件,如下所示:

public class MyControl : Label
{
    // No overriding
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM