在WPF中将字符串转换为控件类型 [英] Convert String to a Control type in WPF

查看:369
本文介绍了在WPF中将字符串转换为控件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在WPF表单中有3个TextBox控件和一个按钮控件.在第一个文本框中,输入任何其他TextBox的名称,然后单击按钮,将焦点设置为相应的TextBox.

我在下面添加了类似的代码.

私有void Button_Click(对象发送者,RoutedEventArgs e)        
{
字符串strControlName = textBox1.Text;
  if(strControlName.Equals("textBox2"))
  {
        textBox2.Focus();<
  }
如果(strControlName.Equals("textBox3"))
  {
        textBox3.Focus();       
 } 
}


但是更简单的方法

私有void Button_Click(对象发送者,RoutedEventArgs e)
{
字符串strControlName = textBox1.Text;
  strControlName.Focus();
}


我的要求是: 
是否可以像在WPF应用程序中的上述示例一样将字符串转换为Control?请分享对此的任何想法.

谢谢
萨拉瓦纳




解决方案

您需要找到该控件,如果findname与其他控件位于堆栈面板中,则findname会为您做到这一点:

http://msdn.microsoft.com/en-us/library /system.windows.frameworkelement.findname.aspx

类似.

对象tb = stackPanel.FindName("textBox2");
    如果(tb是TextBox)
    {
        (文本框)tb.Focus();
    }

如果涉及其他容器,那么这可能会变得有些复杂,因为您需要迭代子对象和其他东西.

在这种情况下,您需要研究VisualTreeHelper FindChild.

http://msdn.microsoft. com/en-us/library/system.windows.media.visualtreehelper(v = vs.110).aspx

.

对于业务应用程序来说,这种机制非常脆弱.


Hi,

I have a 3 TextBox controls and a button control in a WPF form. In the first text box we enter name of any other TextBox and when we click the button, set the focus to corresponding TextBox.

I have added code like in below. 

private void Button_Click(object sender, RoutedEventArgs e)       
{
string strControlName = textBox1.Text;
 if (strControlName.Equals("textBox2"))
  {
        textBox2.Focus(); 
  }
 else if (strControlName.Equals("textBox3"))
 {
        textBox3.Focus();       
 } 
}


But the simpler way for this 

private void Button_Click(object sender, RoutedEventArgs e) 
{
string strControlName = textBox1.Text;
 strControlName.Focus();
}


My requirement is : 
Is it possible to convert string to Control as like in above example in WPF application? Please share any idea on this.

Thanks,
Saravana




解决方案

You need to find the control and findname will do that for you if it's just in a stackpanel with the other controls:

http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.findname.aspx

Something like.

    object tb = stackPanel.FindName("textBox2");
    if (tb is TextBox)
    {
        (TextBox)tb.Focus();
    }

If other containers are involved then this can get a bit complicated as you need to iterate the children and stuff.

In that case you'll want to look into VisualTreeHelper FindChild.

http://msdn.microsoft.com/en-us/library/system.windows.media.visualtreehelper(v=vs.110).aspx

.

This mechanism would be very fragile for a business application.


这篇关于在WPF中将字符串转换为控件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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