yylang1987-old
yylang1987-old

Reputation: 1

WPF, when inherit directly from Control, How to set default property like 'Background' in code?

I'm trying to avoid using XAML in this control for some particular reason.

Then I create a new C# class named MyControl

class MyControl: Control
{
    public MyControl()
    {
        this.BorderBrush = SystemColors.ActiveBorderBrush;
        this.Background = Brushes.Blue;
        this.BorderThickness = new Thickness(1);
    }
}

And I created a WPF window and in XAML and add

xmlns:local="clr-namespace:....."
<local:MyControl Height="186" HorizontalAlignment="Left" Margin="12,12,0,0" x:Name="mycontrol" VerticalAlignment="Top" Width="331" />

but the Background property not working. Any one can help me?

Upvotes: 0

Views: 287

Answers (1)

Clemens
Clemens

Reputation: 128061

From the Remarks section in Control Class:

A Control that does not have a ControlTemplate is not visible in your application, and setting the following properties has no effect unless the ControlTemplate references them explicitly:

  • Background
  • BorderBrush
  • BorderThickness
  • FontFamily
  • FontSize
  • FontStretch
  • FontWeight
  • Foreground
  • HorizontalContentAlignment
  • VerticalContentAlignment

Upvotes: 1

Related Questions