从子用户控件 WPF 更改父用户控件中的文本

  • 本文关键字:控件 用户 文本 WPF c# wpf
  • 更新时间 :
  • 英文 :


如果ParentUserControl包含TextBlock.该ParentUserControl还包含具有TextBoxChildUserControl。我想从ChildTextBox设置ParentUserControl值的TextBlock。我该怎么做?
换句话说,以某种方式访问ParentUserControl,它是TextBlock元素,然后从ChildUserControl修改它的值!

更新
我有一个 xaml 窗口,其中包含一个具有TextBlockParentUserControl。现在我正在运行时加载或添加另一个ChildUserControl。这个新添加的ChildUserControl包含一个ChildTextBox。现在我希望当我在此ChildTexBox中输入一些值时,ParentUserControlTextBlock应该获得该值并自行更新。

假设我们没有遵循任何 MVVM,并且解决此问题的简单方法是,

  1. 创建一个包含文本框的 ChildUserT控件,如下所示,

    <UserControl x:Class="SO52840402.ChildUserControl"
    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" 
    xmlns:local="clr-namespace:SO52607887"
    mc:Ignorable="d" 
    d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
    <TextBox x:Name="ChildTextBox" />
    </Grid>  </UserControl>
    
  2. 创建一个包含 TextBlock 和 ChildUserControl 实例的 ParentUserControl,如下所示,

    <UserControl x:Class="SO52840402.ParentUserControl"
    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" 
    xmlns:local="clr-namespace:SO52607887"
    mc:Ignorable="d" 
    d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
    <Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition />
    </Grid.RowDefinitions>
    <TextBlock x:Name="ParentTextBlock" Text="Hallo World!"/>
    <local:ChildUserControl x:Name="ChildUserControl" Grid.Row="1" />
    </Grid>  </UserControl>
    
  3. 现在为文本框创建一个 TextChanged 事件,该事件位于 ChildUserControl 下,在"初始化组件"之后从 ParentUserControl 构造函数的代码隐藏处,如下所示,

    public ParentUserControl()
    {
    InitializeComponent();
    ChildUserControl.ChildTextBox.TextChanged += OnChildTextBox_TextChanged;
    }
    private void OnChildTextBox_TextChanged(object sender, EventArgs e)
    {
    ParentTextBlock.Text = (sender as TextBox).Text;
    }
    

注意:- 这不是推荐的方法。为了获得最佳方法,请遵循 MVVM 模式并了解您的要求并进行设计。由于您需要来自父用户控件的子用户控件的某些内容,因此最好的方法是将 ViewModel 绑定到父视图和子视图,并在父视图模型中访问子视图模型,并执行"您想要的任何操作"。

最新更新