我设法通过ObservableCollection将我的数据绑定到datagrid和listbox。我还设法使用下面的代码从我的数据网格的第一列获取列表框项。任何人都可以告诉我如何访问第二和第三列中的列表框,因为我只获得包含我的列表框的第一列? (我以为我的FindVisualChild merthod会从数据网格中拉出所有列表框,而不管它们在哪个列中,我可以通过更改标记名称或其他东西来分隔它们 - 我猜错了...)
private void button1_Click(object sender, RoutedEventArgs e)
{
// Update Job Step Grid ListBox
for (int i = 0; i < dataGridJobSteps.Items.Count; i++)
{
DependencyObject obj = dataGridJobSteps.ItemContainerGenerator.ContainerFromIndex(i);
ListBox _listBox = FindVisualChild<ListBox>(obj);
var selectedItems = _listBox.Items;
foreach (var selectedItem in selectedItems)
{
MessageBox.Show(selectedItem.ToString());
}
}
}
public static childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
{
// Search immediate children
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child is childItem)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
答案 0 :(得分:0)
您的FindVisualChild
方法仅返回找到的第一个ListBox
,如果您想查找ListBoxes
中需要修改方法以返回的所有DataGrid
IEnumerable<childItem>
public static IEnumerable<childItem> FindVisualChildren<childItem>(DependencyObject obj) where childItem : DependencyObject
{
// Search immediate children
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child is childItem)
yield return (childItem)child;
else
{
var childOfChild = FindVisualChildren<childItem>(child);
if (childOfChild != null)
{
foreach(var item in childOfChild )
{
yield return item;
}
}
}
}
return null;
}
注意:但是如果你遵循WPF中的MVVM模式,这将比迭代视觉元素容易得多