zoukankan      html  css  js  c++  java
  • 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

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

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

  • 相关阅读:
    关于亮剑,文化大革命的一点感想
    iOS -- block
    runtime -- 方法交换的坑自定义方法不执行
    iOS-UITableViewCell
    iOS debug模式
    iOS 将storybord中的视图与viewcontroller相关联
    gitignore的编写规则
    使用cocopods安装Alamofire后各种报错
    ReactNative--坑--'React/RCTBridgeModule.h' file not found
    12-2描点 学完路径可以对整个工具条做个概括 绘图类已完成
  • 原文地址:https://www.cnblogs.com/Yukang1989/p/2680692.html
Copyright © 2011-2022 走看看