我有一个 ItemsControl 在其模板中使用 DataGrid,如下所示:
<ItemsControl Name="icDists" ItemsSource="{Binding Dists}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding}" Width="150" Margin="5" AutoGenerateColumns="False" IsReadOnly="True">
<DataGrid.Columns>
<DataGridTextColumn Header="Key" Binding="{Binding Key}" Width="1*" />
<DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="1*" />
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
ItemsControl 绑定到Dists
我的模型中的属性如下所示:
ObservableCollection<Dictionary<string, string>> Dists;
如何获取与 Dists 属性中的项目相对应的 DataGrid?我尝试过使用这段代码,它给了我一个 ContentPresenter 但我不知道如何从中获取 DataGrid:
var d = Dists[i];
var uiElement = (UIElement)icDistribucion.ItemContainerGenerator.ContainerFromItem(d);
我尝试过爬上树VisualHelper.GetParent
但找不到 DataGrid。
如果你想做类似的事情,需要搜索 VisualTree。不过我建议您多阅读一些有关 MVVM 模式的内容。但这就是你想要的。
using System.Windows.Media;
private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0)
return null;
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
{
return (T)child;
}
else
{
var result = FindFirstElementInVisualTree<T>(child);
if (result != null)
return result;
}
}
return null;
}
现在,设置 ItemsSource 后,ItemsControl 就准备好了。我只是要在Loaded
event.
private void icDists_Loaded(object sender, RoutedEventArgs e)
{
// get the container for the first index
var item = this.icDists.ItemContainerGenerator.ContainerFromIndex(0);
// var item = this.icDists.ItemContainerGenerator.ContainerFromItem(item_object); // you can also get it from an item if you pass the item in the ItemsSource correctly
// find the DataGrid for the first container
DataGrid dg = FindFirstElementInVisualTree<DataGrid>(item);
// at this point dg should be the DataGrid of the first item in your list
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)