使用VisualTreeHelper擷取DataTemplate中的控制項

來源:互聯網
上載者:User

定義為DataTemplate中的控制項,無法直接通過x:Name的索引方式來擷取,因此必須另想辦法。

在.net庫中有一個VisualTreeHelper類,是專用於涉及視覺化樹狀結構的節點的操作用途。既然控制項也存在於視覺化樹狀結構中,也可以使用這種方式來尋找節點。

貌似還有一種方法,在DataTemplate中有LoadContent的方式,也可以擷取其中的根項目。但我試了幾遍,沒什麼反應,只好暫時作罷。下次再找原因。

下面是一個執行個體代碼。

(1)首先是ListBox的資料來源類樣本:

    public class FileBrowserDataSource : INotifyPropertyChanged    {         #region Data Members        private string m_FileName;        public string FileName        {            get            {                return m_FileName;            }            set            {                if (value != m_FileName)                {                    m_FileName = value;                    NotifyPropertyChanged("FileName");                }            }        }        private string m_CreateDate;        public string CreateDate        {            get            {                return m_CreateDate;            }            set            {                if (value != m_CreateDate)                {                    m_CreateDate = value;                    NotifyPropertyChanged("CreateDate");                }            }        }        #endregion        #region Constructor        public FileBrowserDataSource(string fileName, string date)        {            FileName = fileName;            CreateDate = date;        }        #endregion        #region Event Handler        public event PropertyChangedEventHandler PropertyChanged;        private void NotifyPropertyChanged(String propertyName)        {            PropertyChangedEventHandler handler = PropertyChanged;            if (null != handler)            {                handler(this, new PropertyChangedEventArgs(propertyName));            }        }        #endregion    }

(2)接著是在一個頁面xaml中定義了ListPicker和一個用於測試的button:

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" Height="400" Background="CadetBlue">            <Grid.RowDefinitions>                <RowDefinition Height="Auto"/>                <RowDefinition Height="*"/>            </Grid.RowDefinitions>            <ListBox x:Name="FileListBox" Grid.Row="0"                     ItemsSource="{Binding}"                     Height="200">                <ListBox.ItemTemplate>                    <DataTemplate>                        <StackPanel Orientation="Horizontal">                             <CheckBox  Content="{Binding FileName}" VerticalAlignment="Center"/>                            <TextBlock Margin="20 0 0 0" Text="{Binding CreateDate}" VerticalAlignment="Center"/>                        </StackPanel>                    </DataTemplate>                </ListBox.ItemTemplate>            </ListBox>                        <Button Click="OnButtonClick" Content="Count Selected Files" Grid.Row="1" Height="80" Background="Chartreuse"/>        </Grid>

(3)最後是ListPicer的後台代碼:

    public partial class TestListPicker : PhoneApplicationPage    {        public TestListPicker()        {            InitializeComponent();            List<FileBrowserDataSource> list = new List<FileBrowserDataSource>();            list.Add(new FileBrowserDataSource("headFile","20120924"));            list.Add(new FileBrowserDataSource("midFile", "20120925"));            list.Add(new FileBrowserDataSource("tailFile", "20120925"));            FileListBox.ItemsSource = list;        }        private void OnButtonClick(object sender, EventArgs e)        {            string selectedFiles = string.Empty;            for (int i = 0; i < this.FileListBox.Items.Count; i++)            {                ListBoxItem item = this.FileListBox.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;                TextBlock txtBlock = SearchVisualTree<TextBlock>(item);                CheckBox chkBox = SearchVisualTree<CheckBox>(item);                if (chkBox.IsChecked == true)                {                    selectedFiles += (txtBlock.Text.ToString() + " ");                }            }            if (selectedFiles != string.Empty)            {                selectedFiles = "files selected: " + selectedFiles;                MessageBox.Show(selectedFiles);            }            else            {                MessageBox.Show("No file Selected");            }        }        private T SearchVisualTree<T>(DependencyObject tarElem) where T:DependencyObject        {            var count = VisualTreeHelper.GetChildrenCount(tarElem);            if (count == 0)                return null;            for (int i = 0; i < count; ++i)            {                var child = VisualTreeHelper.GetChild(tarElem, i);                if (child != null && child is T)                {                    return (T)child;                }                else                {                    var res = SearchVisualTree<T>(child);                    if (res != null)                    {                        return res;                    }                }            }            return null;        }}

(4)運行效果:

最後還有一個問題沒有解決,就是在後台代碼中我想動態設定空間的Binding資料來源(通過SetBinding方法),但是失敗了,暫時頭腦有點亂。遲點再解決吧。有高手在這裡的話麻煩指教一下,不勝榮幸。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.