访问 WPF 用户控制值 [英] Access WPF user control value

查看:28
本文介绍了访问 WPF 用户控制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WPF 用户控件和 WPF 表单上的按钮中有 2 个文本框.如何在我使用 WPF 用户控件的主窗体的按钮单击事件上访问这些文本框值

I have 2 text box in WPF user control and button on WPF form. How can I access those textbox value on the button click event of that main form where I am using the WPF user control

推荐答案

首先,请记住 WPF 不是 WinForms -- 理论上你应该数据绑定 您的 TextBoxes 到属性然后更改属性的值,而不是直接访问 TextBoxes!

First of all, keep in mind that WPF is not WinForms -- in theory you should data bind your TextBoxes to properties and then change the value of the properties, instead of accessing the TextBoxes directly!

话虽如此,您所要做的就是命名 UserControl 和 TextBoxes,然后访问它们,如下所示:

That being said, all you have to do is to name the UserControl and the TextBoxes, and then access them, like this:

Int MyUserControl.xaml:

<TextBox x:Name="myTextBox1"/>
<TextBox x:Name="myTextBox2"/>

MyWindow.xaml 中:

<local:MyUserControl x:Name="myUserControlInstance"/>
<Button Content="Click me" Click="Button_Click" />

MyWindow.xaml.cs 中:

private void Button_Click(object sender, RoutedEventArgs e) {
  myUserControlInstance.myTextBox1.Text = "Foo";
  myUserControlInstance.myTextBox2.Text = "Bar";
}

这篇关于访问 WPF 用户控制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆