WPF自定义控件不可见 [英] WPF Custom Controls Are Invisible
问题描述
当我在WPF中创建自定义控件并将其添加到窗口时,在对话框中没有看到任何放置位置。这是我正在做的事情:
When I create a custom control in WPF and add it to a window, I don't see anything where I placed it in the dialog. Here's what I'm doing:
- 创建新的WPF应用程序
- 添加->新项目...->自定义控件(WPF): CustomButton.cs
- 我将CustomButton基类更改为Button而不是Control
- 添加
- 当我运行应用程序或在设计器中查看主窗口时,什么都看不到。
- Create a new WPF Application
- Add -> New Item... -> Custom Control (WPF): "CustomButton.cs"
- I change the CustomButton base class to Button instead of Control
- Add a CustomButton control to my main window.
- When I run the application or view the main window in the designer, I don't see anything.
这是代码的样子。
CustomButton.cs:
CustomButton.cs:
public class CustomButton : Button
{
static CustomButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton),
new FrameworkPropertyMetadata(typeof(CustomButton)));
}
}
MainWindow.xaml:
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:
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中注释掉了静态构造函数,该按钮会突然显示在主窗口中。但是,在所有情况下它看起来都不是很正确(例如,如果我使用工具栏中的按钮)。
I've found two leads as to what's going on, but nothing has clicked yet. When I added the custom control, Visual Studio added Themes/Generic.xaml, but no matter what I try in there, I see no difference on screen. The other thing is that if I comment out the static constructor in CustomButton.cs, all of a sudden the button show up in the main window. It doesn't look quite right in all situations, though (like if I use the button in a toolbar).
推荐答案
是您的自定义控件模板?
Where is your custom control template?
说
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton),
new FrameworkPropertyMetadata(typeof(CustomButton)));
您表示要定义自己的自定义控件。我认为,如果删除该按钮,则会看到您的按钮。
you're indicating you want to defined your own custom control. I think if you remove that, you'll see your button.
这篇关于WPF自定义控件不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!