When I create a custom control in WPF and add it to the window, I don’t see anything where I placed it in the dialog box. That's what I'm doing:
- Create a new WPF application
- Add → New Item ... → Custom Control (WPF): "CustomButton.cs"
- I change the base class CustomButton to Button instead of Control
- Add a CustomButton control to the main window.
- When I launch the application or look at the main window in the designer, I see nothing.
This is 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 found two conclusions about what was happening, but nothing clicked. When I added the user control, Visual Studio added Themes / Generic.xaml, but no matter what I try there, I see no difference on the screen. Another thing is that if I comment on the static constructor in CustomButton.cs, the button will suddenly appear in the main window. In all situations, this does not look quite right (for example, if I use the button on the toolbar).
Jason source share