Wpf Xaml间接查找控件或用x:name来应用控件实例
1.使用树状进行间接查找。
代码如下:
View Code
1 <Grid>
2 <Button Content="Hello" Height="30" Width="50"/>
3 </Grid>
2 <Button Content="Hello" Height="30" Width="50"/>
3 </Grid>
后台代码如下:通过后台代码来寻找控件实例。
如下:
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 }
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,
前台代码如下:
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>
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>
后台代码
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 }
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