VisualTreeHelper使用之ListBox模板DataTemplate中CheckBox选中项(WP7.1)

在最近的WP项目中要导入手机联系人,并且可以勾选添加(WP访问联系人这里不说了),开始设计是,外面ListBox,在DataTemplate中添加CheckBox,当然界面设计完全没问题也很漂亮,但是到后台要读取数据的时候我发现不知所措了,纠结了1个多小时没想到怎么做,最后使用了ListBoxWithCheckBoxes代替我之前的,结果使用起来很简单,很方便。

但是最近我在无意间看到逻辑树和可视化树,网上说可视化树可以遍历模板内容(可视化树概念也存在于WPF 中,它与Silverlight 的可视化树概念类似。 然而,一个显著的差异是WPF 还提供一个附加的筛选器或对象树(称为“逻辑树”)的概念。),一下子就好兴奋,好吧下面我们就开始我们的工作,完成ListBox中CheckBox的选择项遍历:

先定义数据绑定FileBrowserModel 类:

public class FileBrowserModel : INotifyPropertyChanged
    {
        private string _FileName;
        public string FileName
        {
            get
            {
                return _FileName;
            }
            set
            {
                if (value != _FileName)
                {
                    _FileName = value;
                    NotifyPropertyChanged("FileName");
                }
            }
        }

        private string _CreateDate;
        public string CreateDate
        {
            get
            {
                return _CreateDate;
            }
            set
            {
                if (value != _CreateDate)
                {
                    _CreateDate = value;
                    NotifyPropertyChanged("CreateDate");
                }
            }
        }

      

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

注意ListBox绑定的ItemsSource="{Binding FileBrowserModels}" 是FileBrowserModels,它是:

     public ObservableCollection<FileBrowserModel> FileBrowserModels
        {
            get;
            private set;
        }

XAML部分代码:

<ListBox x:Name="FileListBox"
                     ItemsSource="{Binding FileBrowserModels}"
                     Margin="0,-6,-12,0"
                     Height="541">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>                          
                            <TextBlock x:Name="tt" Text="{Binding CreateDate}"></TextBlock>
                            <CheckBox  Content="{Binding FileName}"></CheckBox>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
</ListBox>
绑定好了,之后再Grid里面添加一个Button
 <Button x:Name="btn" Content="btn" Click="btn_Click"></Button>

后台代码如下:

 private void btn_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < this.FileListBox.Items.Count; i++)
            {
                ListBoxItem item = this.FileListBox.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
         //通过VisualTreeHelper去找到TextBlock|Checkbox控件
               TextBlock txtBlock = FindLastElementInVisualTree<TextBlock>(item);
         CheckBox chkBox
= FindFirstElementInVisualTree<CheckBox>(item); //FileBrowserModel filebor = item.DataContext as FileBrowserModel; if (chkBox.IsChecked == true) { MessageBox.Show(chkBox.Content.ToString() + txtBlock.Text.ToString()); } } }
FindFirstElementInVisualTree方法:
View Code
private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
        {
            var count = VisualTreeHelper.GetChildrenCount(parentElement);
            if (count == 0)
                return null;
            for (int i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(parentElement, i);
                if (child != null && child is T)
                {
                    return (T)child;
                }
                else
                {
                    var result = FindFirstElementInVisualTree<T>(child);
                    if (result != null)
                        return result;
                }
            }
            return null;
        }

  FindLastElementInVisualTree方法:

View Code
private T FindLastElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
        {
            var count = VisualTreeHelper.GetChildrenCount(parentElement);
            if (count == 0)
                return null;
            for (int i = count-1; i >= 0; i --)
            {
                var child = VisualTreeHelper.GetChild(parentElement, i);
                if (child != null && child is T)
                {
                    return (T)child;
                }
                else
                {
                    var result = FindFirstElementInVisualTree<T>(child);
                    if (result != null)
                        return result;
                }
            }
            return null;
        }

由于DataTemplate只有两个控件,所以一个从后向前遍历,一个从前向后遍历,其实他的方法都是参考国外一篇文章:

VisualTreeHelper

通过以上的方法,我们可以查找到ListBox中那个CheckBox被选中,以及读取到对应的值;当然在实际的项目中你可能需要读取的值不仅仅是CheckBox一个,这是难道我们需要向DataTemplate中添加多个TextBlock吗??回答当然不是,我们其实有一个CheckBox就足够,我们可以通过FileBrowserModel filebor = item.DataContext as FileBrowserModel;(这里的FileBrowserModel 是数据绑定类)获取当前选中项的对象,通过filebor读取其他字段值;

最后在MSDN参考学习:http://msdn.microsoft.com/zh-cn/library/bb613579.aspx

最后把运行的效果截图给大家:

由于背景有点花,不是很清楚,对不起大家,以上是本人学习一个过程,分享给大家,希望大家提建议,拍砖,共同学习进步。

转载于:https://www.cnblogs.com/Yukang1989/archive/2012/09/11/2680692.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值