在下面的更复杂的实现中,我发现了一个奇怪的行为。
我有一个窗口,包含一个UserControl
。 UserControl
需要带有参数的构造函数,因此在Window调用InitializeComponent()
之后会重新初始化。
<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>
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 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>
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}");
}
}
Parameter-less constructor creates control: 66824994
Control is now referenced: 5560998 with Foo: Bar
单击按钮
This method was invoked on: 66824994 with Foo value: ""
问题
为什么UserControl
实例未更改?控制台输出显示该字段已更新,以引用“参数化”构造函数的结果,但是在原始实例上调用了按钮单击。非常感谢!
在下面的更复杂的实现中,我发现了一个奇怪的行为。我有一个包含UserControl的窗口。 UserControl需要带有参数的构造函数,因此是...
感谢您,并感谢@Clemens在以上评论中提供的答案。总结: