1.向ListBox中放入其他控件
XAML:
C#:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace ItemsControls{ ////// MainWindow.xaml 的交互逻辑 /// public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } ////// 找出父级容器 /// /// /// private void buttonVictor_Click(object sender, RoutedEventArgs e) { Button btn = sender as Button; DependencyObject level1 = VisualTreeHelper.GetParent(btn); DependencyObject level2 = VisualTreeHelper.GetParent(level1); DependencyObject level3 = VisualTreeHelper.GetParent(level2); MessageBox.Show(level1.GetType().ToString()); MessageBox.Show(level2.GetType().ToString()); MessageBox.Show(level3.GetType().ToString()); } }}
结果:
知识点:
1)ListBox的父级容器是ListBoxItem
2)把数据集交给ListBox后,无需标明ListBoxItem,它会自动包装整的
3)VisualTreeHelper类提供一些实用工具方法,用于执行涉及可视化树中的节点的常规任务。
2.放入其他数据
XAML:
C#:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Shapes;namespace ItemsControls{ ////// Window1.xaml 的交互逻辑 /// public partial class Window1 : Window { ListempList = new List (){ new Employee(){Id=1,Name="Tim",Age=21}, new Employee(){Id=2,Name="Tom",Age=22}, new Employee(){Id=3,Name="Guo",Age=23} }; public Window1() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { this.listBoxEmployee.DisplayMemberPath = "Name";//设置在ListBox上显示的属性 this.listBoxEmployee.SelectedValuePath = "Id";//设置ListBox选中后的属性值 this.listBoxEmployee.ItemsSource = empList; } }}
结果:
知识点:
1)DisplayMemberPath设置要在ListBox上显示的属性
2)SelectedValuePath设置选中后的值的属性
3)ItemsSource设置数据源