当我在WPF中创建自定义控件并将其添加到窗口中时,在对话框中放置的位置上看不到任何内容。这是我所做的:
CustomButton.cs:
- 创建一个新的WPF应用程序
- 添加 -> 新项目... -> 自定义控件(WPF):"CustomButton.cs"
- 我将CustomButton基类从Control更改为Button
- 将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中的静态构造函数,突然间按钮就出现在主窗口中了。但在某些情况下它看起来不太对(比如我在工具栏中使用该按钮)。