I made a very simple test project:
MainWindow.xaml:
<Window x:Class="Test.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Test" Title="MainWindow" Height="350" Width="525" VerticalAlignment="Center" HorizontalAlignment="Center"> <StackPanel x:Name="mainPanel" /> </Window>
MainWindow.xaml.cs:
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace Test { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); MyTextBox myTextBox = new MyTextBox("some text here"); mainPanel.Children.Add(myTextBox); } } }
MyTextBox.cs:
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace Test { class MyTextBox : TextBox { static MyTextBox() { MyTextBox.BackgroundProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(Brushes.Red)); } public MyTextBox(string Content) { Text = Content; } } }
to check the metadata override function.
Now the problem is: it does not work as I expected ...
indeed, the background of MyTextBox is white, not red.
I researched and tried this as a constructor for my custom class:
public MyTextBox(string Content) { Text = Content; Background = Brushes.Blue; ClearValue(BackgroundProperty); }
Now here is what I learned when debugging:
in the main class:
MyTextBox myTextBox = new MyTextBox("some text here");
we will move on to the static constructor of the custom class, then in the instance constructor:
Text = Content; → Background = red
Background = Brushes.Blue; → Background = blue
ClearValue(BackgroundProperty); → Background = red again (as expected)
back to the main class:
mainPanel.Children.Add(myTextBox);
... and right after this line of code myTextBox.Background is white.
Question: Why?
why is this parameter set to white when i add it to mainPanel ??? I can not find a logical explanation for this ...
Also, if I add some more code where I do something like: myTextBox.Background = Brushes.Blue; and then myTextBox.ClearValue(MyTextBox.BackgroundProperty); , it turns blue, and then again white, not red.
I do not understand.