[Silverlight学习笔记]如何获取ItemsControl的DataTemplate中定义的控件?

开发环境:VisualStudio2010 +Silverlight4

新建一个test.xaml,并添加ComboBox组合框控件,其Xaml代码如下:

<ComboBox x:Name="cmbBoxCategory" Height="28" Margin="105,69,182,0" VerticalAlignment="Top" SelectionChanged="cmbBoxCategory_SelectionChanged" DataContext="{StaticResource SharingObjectCategoryDataSource}" ItemsSource="{Binding CategoryCollection }" >
            <ComboBox.ItemTemplate>
                <DataTemplate x:Name="cmbTemplate">
                    <StackPanel Orientation="Horizontal">
                        <TextBox x:Name="txtID" Text="{Binding Path=ID}"/>
                        <Image Source="{Binding Path=ImagePath}"/>
                        <TextBlock x:Name="tbCategoryName" Text="Name"/>
                    </StackPanel>                    
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

那么我们如何获取DataTemplate中的名为txtID的TextBox控件或者其它控件呢?

      在test.xaml.cs文件中不能够直接引用名为txtID的TextBox控件,即this.txtID是不能访问的,因为txtID只属于DataTemplate模板的名称空间范围内(类似于参数的作用域),可参看Silverlight4文档的TemplatePartAtrribute。我们如何获得DataTemplate的TextBox控件呢?可用如下方式获得:

方法一:

TextBox txtBox = (TextBox)VisualTreeHelper.GetChild(this.cmbTemplate.LoadContent(), 0);
// this.cmbTemplate.LoadContent()是获取cmbTemplate名的DataTemplate的内容,该例中获
//得的是StackPanel,再通过VisualTreeHelper.GetChild()方法获得属于该StackPanel的控件,
//可参看Silverlight4文档的LoadContent()方法的使用

方法二:

StackPanel panel = (StackPanel)this.cmbTemplate.LoadContent();
TextBlock tbCategory=panel.FindName("tbCategoryName") as TextBlock;
//可参看Silverlight4文档的FindName()方法的使用

对于

TextBox txtBox = (TextBox)VisualTreeHelper.GetChild(this.cmbTemplate.LoadContent(), 0);

因为它的Text的值是绑定数据源的ID属性(如:{Binding Path=ID}),通过程序运行动态生成的值,因此通过这两种方式获得的TextBox的Text是空值,而对于tbCategoryName名的TextBlock,因为它的Text值是固定的“Name”字符串,因此通过这两种方法获得的TextBlock的Text值为“Name”。

如果我们想获得选中的ComboBoxItem的TextBox的值或者Image的Source值,则可通过如下方式获得:

//test.xaml.cs代码
private void cmbBoxCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.cmbBoxCategory.SelectedItem!=null)
            {
                ComboBox item = sender as ComboBox;
	     Category cat = (Category)this.cmbBoxCategory.SelectedItem;
//Category类为cmbBoxCategory组合框绑定的数据源类,然后再通过cat获取该类中的ImagePath属性即可
	       this.imgObject.Source = new BitmapImage(new Uri(cat.ImagePath, UriKind.Relative));
//imgObject为test.xaml中的一个Image控件				
            }
     }

可能有更好的方法获得绑定数据源时动态生成的值,本人不才,还未想出该方法,可讲究用上面的方法获得,如果找到了相应方法就做更新。

转载于:https://www.cnblogs.com/wackelbh/archive/2010/11/12/1984043.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值