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:
- 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.
Here’s what the code looks like.
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>
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?
By saying
you’re indicating you want to defined your own custom control. I think if you remove that, you’ll see your button.