如何从后面包含窗口的代码中更改UserControl的实例?

问题描述 投票:0回答:1

在下面的更复杂的实现中,我发现了一个奇怪的行为。

我有一个窗口,包含一个UserControlUserControl需要带有参数的构造函数,因此在Window调用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>

控制CS
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 CS
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需要带有参数的构造函数,因此是...

c# wpf user-controls
1个回答
0
投票

感谢您,并感谢@Clemens在以上评论中提供的答案。总结:

© www.soinside.com 2019 - 2024. All rights reserved.