Wpf Xaml间接查找控件或用x:name来应用控件实例

1.使用树状进行间接查找。

  代码如下:

 

ExpandedBlockStart.gif View Code
1  < Grid >
2           < Button Content = " Hello "  Height = " 30 "  Width = " 50 " />
3       </ Grid >

 

 后台代码如下:通过后台代码来寻找控件实例。

如下:

ExpandedBlockStart.gif View Code
1    public  win()
2          {
3              InitializeComponent();
4              Grid gd  =   this .Content  as  Grid;
5              Button btn  =  gd.Children[ 0 as  Button;
6            
7              btn.Content  =   " wpf " ;
8 
9          }

 

 运行结果如下:说明button最终的显示结果取决于后台代码:

 

 2.使用x:name来访问xaml对象实例。xaml中的所有的控件的属性和事件都都属于FrameworkElement,

前台代码如下:

ExpandedBlockStart.gif View Code
 1  < Window x:Class = " wpf.Name "
 2          xmlns = " http://schemas.microsoft.com/winfx/2006/xaml/presentation "
 3           xmlns:local = " clr-namespace:wpf "
 4          xmlns:x = " http://schemas.microsoft.com/winfx/2006/xaml "
 5         
 6          Title = " Name "  Height = " 300 "  Width = " 300 " >
 7         
 8       < Grid >
 9           < Button x:Name = " btn "  Width = " 80 "  Height = " 50 "   Click = " Btn_Click " >
10               < Button.Content >
11                   < local:Student x:Name = " Stu " />
12               </ Button.Content >
13              
14           </ Button >
15          
16       </ Grid >
17  </ Window >

 

 

ExpandedBlockStart.gif 后台代码
 1  namespace  wpf
 2  {
 3       ///   <summary>
 4       ///  Name.xaml 的交互逻辑
 5       ///   </summary>
 6       public   partial   class  Name : Window
 7      {
 8           public  Name()
 9          {
10              InitializeComponent();
11              btn.Content  =   " my name " ;
12              Stu.Sno  =   " 20070711123 " ;
13          }
14 
15           private   void  Btn_Click( object  sender, RoutedEventArgs e)
16          {
17              MessageBox.Show(btn.Name);
18          }
19      }
20 
21       public   class  Student
22      {
23           public   string  Sno {  get set ; }
24      }
25  }

 说明通过创建Student来先说明x:Name与Name的区别。

   对于xaml来说,x:Name与name是一样的。都是实例对象的引用。

  而对于自己创建的类,是不一样的。

 

 

参考:http://www.cnblogs.com/prism/archive/2010/09/13/1824789.html

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值