首页 文章

WPF自定义控件是不可见的

提问于
浏览
5

当我在WPF中创建自定义控件并将其添加到窗口时,我没有看到任何将其放在对话框中的位置 . 这就是我正在做的事情:

  • 创建一个新的WPF应用程序

  • 添加 - >新项目... - >自定义控件(WPF):"CustomButton.cs"

  • 我将CustomButton基类更改为Button而不是Control

  • 将CustomButton控件添加到主窗口 .

  • 当我运行应用程序或查看设计器中的主窗口时,我什么都看不到 .

这是代码的样子 .

CustomButton.cs:

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

MainWindow.xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:WpfApplication1">
    <Grid>
        <my:CustomButton Content="Hello World" x:Name="customButton1"
                         HorizontalAlignment="Left" VerticalAlignment="Top" Margin="150,175,0,0" />
    </Grid>
</Window>

Generic.xaml:

<Style TargetType="{x:Type local:CustomButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustomButton}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我找到了两个关于发生了什么的线索,但还没有点击过 . 当我添加自定义控件时,Visual Studio添加了Themes / Generic.xaml,但无论我在那里尝试什么,我都看不到屏幕上的差异 . 另一件事是,如果我在CustomButton.cs中注释掉静态构造函数,那么按钮会突然显示在主窗口中 . 但是在所有情况下看起来都不正确(就像我使用工具栏中的按钮一样) .

2 回答

  • 10

    您的自定义控件模板在哪里?

    通过说

    DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton),
            new FrameworkPropertyMetadata(typeof(CustomButton)));
    

    你表明你想要定义自己的自定义控件 . 我想如果你删除它,你会看到你的按钮 .

  • 6

    我想你已经找到了解决问题的方法 . 但是,对于这种情况,其他任何人都会遇到与您相同的问题:可能只解释为什么自定义控件没有显示,尽管创建它的所有步骤都已正确完成,正如您所做的那样,是一个缺失的条目AssemblyInfo.cs . 该文件必须包含以下条目:

    [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly))]
    

    如果没有此条目,将忽略generic.xaml文件,因此找不到default-control-template,因此控件根本不会获得控件模板,因此不会显示 . 这也解释了为什么在禁用静态构造函数时控件突然出现的原因 . 这条线:

    DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton)));
    

    告诉控件使用自己的默认样式而不是从其基类继承它 . 因此,如果没有这一行,CustomButton将只重用Button类的默认控件模板,结果是,您写入generic.xaml的任何内容都不会对CustomButton产生任何影响 .

相关问题