【问题标题】:WPF Setting Content for Custom Control自定义控件的 WPF 设置内容
【发布时间】:2019-10-14 04:53:11
【问题描述】:

在我的 WPF 应用程序中,我在多个页面上有多个标签,它们看起来都一样,但在程序运行期间可能会改变样式(一次全部)。

经过大量在线搜索后,我浏览了 Window.Resources 模板和用户控件(在程序运行期间可能进行更改时,它们都不能很好地用于样式设置)并且目前已选择 CustomControl。但是,我不知道如何设置它的内容。有些标签会有一个带有多个孙子的包装面板,有些标签只有文字。但是,无论哪种方式,我都无法解决。这似乎是一个超越标签的程序。我错过了什么?

我的控件(刚改成继承自Label):

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

Themes.Generic.xaml 没有变化

My 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" />

如何让该内容显示出来?

编辑:删除 DefaultStyleKeyProperty.OverrideMetadata 有效。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    如果您要在您的Themes/Generic.xaml 中覆盖其DefaultStyleKeyProperty,您应该为您的自定义控件定义一个默认模板。基于Label的默认模板:

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

    或者,您可以删除 DefaultStyleKeyProperty 的覆盖并保留您的控制权,如下所示:

    public class MyControl : Label
    {
        // No overriding
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-24
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多