1、WPF 获得DataTemplate中的控件, 下面这个示例是从ListBox中获得ListBoxItem模板的控件信息。
前台代码:
<!--获得模板中的控件--> <ListBox Margin="12,32,0,0" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" Name="listBox1" SelectedIndex="0" Height="186" VerticalAlignment="Top" HorizontalAlignment="Left" Width="287"> <ListBox.ItemTemplate> <DataTemplate x:Name="gridDataTemplate"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.5*"/> <ColumnDefinition Width="0.5*"/> <ColumnDefinition Width="0.5*"/> <ColumnDefinition Width="0.5*"/> </Grid.ColumnDefinitions> <TextBlock Text="{Binding Path=ID}"/> <TextBlock Grid.Column="1" x:Name="myName" Text="{Binding Path=Name}"/> <TextBlock Grid.Column="2" Text="{Binding Path=Age}" Background="{Binding Path=Age, Converter={StaticResource BackgroundConverter}}"/> <CheckBox Grid.Column="3" x:Name="myCheckBox" IsChecked="{Binding Path= ISBoy, Converter={StaticResource BoolConverter}}"/> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
资源:
<Window.Resources> <Con:BackgroundConverter x:Key="BackgroundConverter"/> <Con:BoolConverter x:Key="BoolConverter"/> </Window.Resources>
<Button Height="23" HorizontalAlignment="Left" Margin="35,251,0,0" Name="button1" VerticalAlignment="Top" Width="209" Click="button1_Click">GetControlFromDataTemplate</Button>
后台代码:
public Window1() { InitializeComponent(); listBox1.DataContext = GetDataTable(); }
Click事件:关键代码
private void button1_Click(object sender, RoutedEventArgs e) { ListBoxItem myListBoxItem = (ListBoxItem)listBox1.ItemContainerGenerator.ContainerFromItem(listBox1.SelectedItem); ContentPresenter contentpresenter = FindFirstVisualChild<ContentPresenter>(myListBoxItem); DataTemplate MyDataTemplate = contentpresenter.ContentTemplate; TextBlock myTextBlock = MyDataTemplate.FindName("myName", contentpresenter) as TextBlock; if (myTextBlock != null) { MessageBox.Show(myTextBlock.Text); } }
数据源:当然也可以自己连接数据库获得数据源
private DataTable GetDataTable() { DataTable data = new DataTable("MyDataTable"); DataColumn ID = new DataColumn("ID");//第一列 ID.DataType = System.Type.GetType("System.Int32"); //ID.AutoIncrement = true; //自动递增ID号 data.Columns.Add(ID); //设置主键 DataColumn[] keys = new DataColumn[1]; keys[0] = ID; data.PrimaryKey = keys; data.Columns.Add(new DataColumn("Name",typeof(string)));//第二列 data.Columns.Add(new DataColumn("Age",typeof(string)));//第三列 data.Columns.Add(new DataColumn("ISBoy", typeof(Int16)));//第三列 data.Rows.Add(1," XiaoM"," 20", 1); data.Rows.Add(2," XiaoF"," 122", 0); data.Rows.Add(3," XiaoA", " 29", 1); data.Rows.Add(4," XiaoB", " 102", 0); return data; }
值转换:BackgroundConverter类是改变颜色,BoolConverter是将Bool互相转换Int
public class BackgroundConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Color color = new Color(); int num = int.Parse(value.ToString()); if (num > 100) color = Colors.Yellow; else if (num < 50) color = Colors.LightGreen; else color = Colors.LightPink; return new SolidColorBrush(color); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } public class BoolConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool flag = false; if (1 == int.Parse(value.ToString())) { flag = true; } if( 0 == int.Parse(value.ToString())) flag = false; return flag; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if ((bool)value) { return 1; } else return 0; } #endregion }
//关键函数
public T FindFirstVisualChild2<T>(DependencyObject obj, string childName) where T : DependencyObject { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child != null && child is T && child.GetValue(NameProperty).ToString() == childName) { return (T)child; } else { T childOfChild = FindFirstVisualChild2<T>(child, childName); if (childOfChild != null) { return childOfChild; } } } return null; }
效果图: 当选中第一项,然后单击"GetControlFromDataTemplate"按钮,则弹出第一项中控件的内容XiaoM。