【发布时间】:2011-07-14 15:35:50
【问题描述】:
当我在 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 中的静态构造函数,按钮会突然出现在主窗口中。不过,它在所有情况下看起来并不完全正确(例如,如果我使用工具栏中的按钮)。
【问题讨论】:
标签: wpf custom-controls