In a more complex implementation of the below, I discovered a strange behavior.
I have a window, containing a UserControl
. The UserControl
requires a constructor with parameters, and is therefore reinitialized after the Window has called InitializeComponent()
.
Control XAML
<UserControl x:Class="TEMP5.MyControl"
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="33" d:DesignWidth="48">
<Grid>
<Button Content="Click"
Width="40" Height="25" Margin="4"
Click="Button_Click"/>
</Grid>
</UserControl>
Control C# code
public partial class MyControl : UserControl
{
public string Foo { get; set; }
public MyControl()
{
InitializeComponent();
}
public MyControl(string foo): this()
{
Foo = foo;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine($"This method was invoked on: {this.GetHashCode()} with Foo value: \"{Foo}\"");
}
}
Window XAML
<Window x:Class="TEMP5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TEMP5"
mc:Ignorable="d"
Title="MainWindow" Height="auto" Width="auto">
<local:MyControl x:Name="myControl"/>
</Window>
Window C# code
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Console.WriteLine($"Parameter-less constructor creates control: {myControl.GetHashCode()}");
myControl = new MyControl("Bar");
Console.WriteLine($"Control is now referenced: {myControl.GetHashCode()} with Foo: {myControl.Foo}");
}
}
Console Output
Parameter-less constructor creates control: 66824994
Control is now referenced: 5560998 with Foo: Bar
Clicks the button
This method was invoked on: 66824994 with Foo value: ""
Question
Why is the UserControl
instance not changed? The console output shows that the field is updated to reference the result of the "parametered" constructor, yet the button click is invoked on the original instance.