访问WPF用户控制值
首先这些文本框的值,请记住,WPF不是的WinForms - 理论上你应该数据绑定您的TextBoxes属性,然后更改属性的值,而不是直接访问TextBoxes!
话虽这么说,所有你需要做的就是命名的用户控件和文本框,然后访问它们,就像这样:
诠释MyUserControl.xaml:
<TextBox x:Name="myTextBox1"/>
<TextBox x:Name="myTextBox2"/>
在MyWindow.xaml:
<local:MyUserControl x:Name="myUserControlInstance"/>
<Button Content="Click me" Click="Button_Click" />
在MyWindo w.xaml.cs:
private void Button_Click(object sender, RoutedEventArgs e) {
myUserControlInstance.myTextBox1.Text = "Foo";
myUserControlInstance.myTextBox2.Text = "Bar";
}
在用户控件,使得它返回一个字符串两个公共属性:
public property Textbox1Text
{
get { return TextBox1.Text; }
}
然后从文本框控件将文本的主要形式是可见的。
或者更好的选择:有一个usercontrol可以引发的事件,称之为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;
或更好,你可以参加一个路由事件 - 但坚持基础知识。
订阅一个事件似乎是一个更好的选择,如上面的slugster所建议的。如果你使用这种方法,你可以在同一个窗口中拥有同一个用户控件的多个实例,但是根据它们来自哪个用户控件来处理它们。
作为一个例子,您可以拥有地址类型的用户控件,它可以包含发件人地址和收件人地址,这些地址可能具有像街道,城市,州等相同的字段。但发件人地址或邮件地址更新时可能会有不同的行为。
希望这会有所帮助。
Nilesh制作Gule
http://nileshgule.blogspot.com
为了您的具体问题,我可以建议你一个具体的解决方案。这不能被视为一般。
您的问题是阅读您的用户控件中的文本框的内容按钮单击。
以下是解决方案。
在此解决方案中,将会有两个xaml文件及其相应的.cs文件。
逻辑: - 固有的逻辑是遍历用户控件中的视觉效果,找到文本框,在按钮单击时读取文本。
所以这里是代码...
-
Window.xaml - 这是我们的主窗口。这包含1个按钮和用户控件的对象引用。
<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);
}
}
}
上面的代码是遍历用户控件中的可视元素。
用户控件的.cs文件不需要。
现在,当你点击按钮,你可以看到你已经进入了MessageBox。
快乐编码...
请标记为答案,如果这可以解决您的问题。
试试这个:
private void Button_Click(object sender, RoutedEventArgs e)
{
string myTextboxValue = this.tbInput.Text;
}