Expander 中 ContentTemplate 绑定数据,新手谢谢
<!--Expander内容模板开始--> <controlsToolkit:Expander.ContentTemplate> <DataTemplate> <StackPanel HorizontalAlignment="Left"> <ListBox x:Name="lsbNodeList" Margin="5" MinHeight="100" MinWidth="100" Opacity="0" > <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=AreaName}" Margin="5" Width="100" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </StackPanel> </DataTemplate> </controlsToolkit:Expander.ContentTemplate> <!--Expander内容模板结束-->
public ObservableCollection<TravelNode> travlnodes = new ObservableCollection<TravelNode>();
public class TravelNode : INotifyPropertyChanged { private string _areaname; public TravelNode(string areaname) { this.AreaName = areaname; } public string AreaName { get { return _areaname; } set { if (string.Compare(_areaname, value) == 0) return; _areaname = value; OnPropertyChanged("AreaName"); } } protected virtual void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #region INotifyPropertyChanged 成员 public event PropertyChangedEventHandler PropertyChanged; #endregion }
private void MainPage_Loaded(object sender, RoutedEventArgs e) { travlnodes.Add(new TravelNode("wgewgwg")); travlnodes.Add(new TravelNode("wgewgwewgwg")); travlnodes.Add(new TravelNode("wgewgwg")); travlnodes.Add(new TravelNode("wgewegwegwgwg")); travlnodes.Add(new TravelNode("wgewjjgwg")); travlnodes.Add(new TravelNode("wgerjjwgwg")); travlnodes.Add(new TravelNode("wgetrjwgwg")); travlnodes.Add(new TravelNode("wehewhwhhmt")); List<ListBox> lbs = this.GetChildObjects<ListBox>(this.sampleExpander.ContentTemplate.LoadContent(), ""); if (lbs.Count > 0) { lbs[0].ItemsSource = travlnodes; } } /// <summary> /// 查询指定的子控件,name 为空所有子控件 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="name"></param> /// <returns></returns> public List<T> GetChildObjects<T>(DependencyObject obj, string name) where T : FrameworkElement { DependencyObject child = null; List<T> childList = new List<T>(); for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++) { child = VisualTreeHelper.GetChild(obj, i); if (child is T && (((T)child).Name == name || string.IsNullOrEmpty(name))) { childList.Add((T)child); } childList.AddRange(GetChildObjects<T>(child, "")); } return childList; }