Open rainit2006 opened 7 years ago
点击ListBox里包含的button,让ListBox添加item元素
private void AddItem(object sender, RoutedEventArgs e)
{
DependencyObject dpo = sender as DependencyObject;
if (dpo != null)
{
var ruleItemListBox = VisualTreeUtilities.FindVisualParent<ListBox>(dpo);
ObservableCollection<Customer> groupDataSource = ruleItemListBox.ItemsSource as ObservableCollection<Customer>;
groupDataSource.Add(new Customer("New", "new1",
"xxxxxx, xxxxx", "10"));
}
}
其中VisualTreeUtilities.FindVisualParent函数是自定义的类和函数,里面实际上用到的是:
public static class VisualTreeUtilities
{
public static parentControl FindVisualParent<parentControl>(DependencyObject obj) where parentControl : DependencyObject
{
if (null == obj)
{
return null;
}
DependencyObject parent = VisualTreeHelper.GetParent(obj);
if (null != parent && parent is parentControl)
{
return (parentControl)parent;
}
else
{
parentControl parentOfParent = FindVisualParent<parentControl>(parent);
if (null != parentOfParent)
{
return parentOfParent;
}
}
return null;
}
代码:https://drive.google.com/drive/u/0/folders/0B3d5yQ5lBDHGWV9DQmszWEVVa0U
--- Sample: ----- xaml里定义一个ListBox的Style。这个ListBox里包含了textbox, button等控件
再定义一个ListItem的Style。每个Item里包含textblock,textbox等控件。
在cs里定义数据源Model类
在ListBox控件里指定上面定义的Style,和DataSource。
<ListBox Name="listbox1" ItemsSource="{Binding Path=Customers}" Style="{StaticResource listboxStyle}" ItemContainerStyle="{StaticResource listItemStyle}"/>