Jas*_*son 5 wpf custom-controls
当我在WPF中创建自定义控件并将其添加到窗口时,我没有看到任何将其放置在对话框中的位置.这是我正在做的事情:
这是代码的样子.
CustomButton.cs:
public class CustomButton : Button
{
static CustomButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton),
new FrameworkPropertyMetadata(typeof(CustomButton)));
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我找到了两个关于发生了什么的线索,但还没有点击.当我添加自定义控件时,Visual Studio添加了Themes/Generic.xaml,但无论我在那里尝试什么,我都看不到屏幕上的差异.另一件事是,如果我在CustomButton.cs中注释掉静态构造函数,那么按钮会突然显示在主窗口中.但是在所有情况下它看起来都不正确(就像我使用工具栏中的按钮一样).
Jef*_*eff 10
您的自定义控件模板在哪里?
通过说
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton),
new FrameworkPropertyMetadata(typeof(CustomButton)));
Run Code Online (Sandbox Code Playgroud)
你表明你想要定义自己的自定义控件.我想如果你删除它,你会看到你的按钮.
小智 10
我想你已经找到了解决问题的方法.但是,对于这种情况,其他任何人都会遇到与您相同的问题:可能只解释为什么自定义控件没有显示,尽管创建它的所有步骤都已正确完成,正如您所做的那样,是一个缺少的条目AssemblyInfo.cs.该文件必须包含以下条目:
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly))]
Run Code Online (Sandbox Code Playgroud)
如果没有此条目,将忽略generic.xaml文件,因此找不到default-control-template,因此控件根本不会获得控件模板,因此不会显示.这也解释了为什么在禁用静态构造函数时控件突然出现的原因.这条线:
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton)));
Run Code Online (Sandbox Code Playgroud)
告诉控件使用自己的默认样式而不是从其基类继承它.因此,如果没有这一行,CustomButton将只重用Button类的默认控件模板,结果是,您写入generic.xaml的任何内容都不会对CustomButton产生任何影响.