我在WPF用户控件中有两个文本框和一个按钮,我想在使用该WPF用户控件的主表单上的按钮单击事件中访问这些文本框的值。
话虽如此,您只需为UserControl和TextBoxes命名,然后像这样访问它们:
在MyUserControl.xaml中:
<TextBox x:Name="myTextBox1"/>
<TextBox x:Name="myTextBox2"/>
<local:MyUserControl x:Name="myUserControlInstance"/>
<Button Content="Click me" Click="Button_Click" />
private void Button_Click(object sender, RoutedEventArgs e) {
myUserControlInstance.myTextBox1.Text = "Foo";
myUserControlInstance.myTextBox2.Text = "Bar";
}
在用户控件中,创建两个返回字符串的公共属性:
public property Textbox1Text
{
get { return TextBox1.Text; }
}
那么文本框控件中的文本将会在主窗体上可见。
或者更好的选择是:添加一个用户控件可以触发的事件,称其为TextChanged
。当然,你肯定想为它取一个更好的名字,所以我们假设你的第一个文本框是设计用于用户输入姓名的,那么就称这个事件为NameTextChanged
,然后你的事件将会像这样:
public MainWindow()
{
InitializeComponent();
TextBox1.TextChanged += new TextChangedEventHandler(TextBox1_TextChanged);
}
private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (NameTextChanged!= null)
this.NameTextChanged(this, e);
}
public event TextChangedEventHandler NameTextChanged;
试试这个:
private void Button_Click(object sender, RoutedEventArgs e)
{
string myTextboxValue = this.tbInput.Text;
}
Window.xaml - 这是我们的主窗口。它包含一个按钮和用户控件的对象引用。
<Grid>
<StackPanel Orientation="Vertical">
<Button x:Name="clickThis"
Height="30"
Width="70"
Content="Click Me!!"
Click="clickThis_Click" />
<local:TxtBoxedUC x:Name="UC" />
</StackPanel>
</Grid>
TxtBoxedUC.xaml - 这是我们的用户控件。它包含两个文本框。
<Grid>
<StackPanel Orientation="Vertical">
<TextBox x:Name="txt1"
Width="150"
Height="30" />
<TextBox x:Name="txt2"
Width="150"
Height="30" />
</StackPanel>
</Grid>
Window1.xaml.cs - 它包含按钮单击方法以及迭代用户控件中可视元素的方法。
private void clickThis_Click(object sender, RoutedEventArgs e)
{
GetVisual(UC);
}
private void GetVisual(UIElement currentVisual)
{
int count = VisualTreeHelper.GetChildrenCount(currentVisual);
if (count > 0)
{
for (int i = 0; i < count; i++)
{
UIElement uiElement = VisualTreeHelper.GetChild(currentVisual, i) as UIElement;
if (uiElement != null)
{
if (uiElement.GetType() == typeof(TextBox))
{
TextBox txt = uiElement as TextBox;
MessageBox.Show(txt.Text);
}
}
GetVisual(uiElement);
}
}
}
如slugster所建议的,订阅事件似乎是更好的选择。如果您使用此方法,可以在同一窗口中拥有多个相同的用户控件,但根据它们来自哪个用户控件,可以以不同的方式处理它们。
例如,您可以拥有地址类型的用户控件,该控件可以具有发件人地址和收件人地址,这些地址可能具有相同的字段,如街道、城市、州等。但当更新发件人地址或收件人地址时,可以以不同的方式运作。
希望这可以帮助到您。
Nilesh Gule
http://nileshgule.blogspot.com