I created my own user control with dependency properties and added it to my main window, where I now want to be able set the dependency properties. The properties are not taking the value I set in the XAML of the main window and I am not sure what I am missing. In the code I set the default value for the FillBrush property to Yellow. In the XAML I set it to Red. When I click the Test button, it shows the property to be Yellow. Here is the code:
Window XAML
<Window x:Class="Test.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:test="clr-namespace:Test"
Title="Window2" Height="200" Width="600">
<StackPanel>
<test:TestUserControl x:Name="myControl"
FillBrush="Red" VerticalAlignment="Center" Margin="20"/>
<Button Height="24" Width="300" Content="Test" Click="Button_Click" />
<TextBox x:Name="debugTextBox" Margin="20"/>
</StackPanel>
</Window>
Window Code Behind
public partial class Window2 : Window
{
public static readonly DependencyProperty FillBrushProperty =
DependencyProperty.Register("FillBrush", typeof(Brush), typeof(Window2),
new UIPropertyMetadata(Brushes.Yellow));
public Brush FillBrush
{
get { return (Brush)GetValue(FillBrushProperty); }
set { SetValue(FillBrushProperty, value); }
}
public Window2() { InitializeComponent(); }
private void Button_Click(object sender, RoutedEventArgs e)
{
this.debugTextBox.Text =
"Red: " + Brushes.Red +
" Yellow: " + Brushes.Yellow +
" Actual: " + this.FillBrush;
}
}
User Control XAML
<UserControl x:Class="Test.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<TextBlock Text="User Control"/>
</UserControl>
User Control Code Behind
public partial class TestUserControl : UserControl
{
public static readonly DependencyProperty FillBrushProperty =
DependencyProperty.Register("FillBrush", typeof(Brush), typeof(TestUserControl),
new UIPropertyMetadata(Brushes.Cyan));
public Brush FillBrush
{
get { return (Brush)GetValue(FillBrushProperty); }
set { SetValue(FillBrushProperty, value); }
}
public TestUserControl()
{
InitializeComponent();
}
}
What am I missing?
In the XAML you are setting the
Fillbrushvalue onTestUserControlto Red, but when the button is clicked it shows theFillbrushvalue forWindow2, notTestUserControl. And since theFillbrushvalue forWindow2is not set in XAML it still has the default value of Yellow.