【问题标题】:Obtain DataGrid inside ItemsControl from the binded item从绑定项中获取ItemsControl内的DataGrid
【发布时间】:2016-03-11 22:23:52
【问题描述】:

我有一个 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;

如何获取与 Diss 属性中的项目对应的 DataGrid?我试过这段代码,它给了我一个 ContentPresenter 但我不知道如何从中获取 DataGrid:

var d = Dists[i];
var uiElement = (UIElement)icDistribucion.ItemContainerGenerator.ContainerFromItem(d);

我尝试使用 VisualHelper.GetParent 向上爬树,但找不到 DataGrid。

【问题讨论】:

  • 为什么需要获取datagrid?如果您进行了适当的绑定和通知,您需要的所有数据都在 Diss 集合中。
  • 我需要手动调用 DataGrid 上的事件。

标签: c# wpf itemscontrol


【解决方案1】:

如果你想做这样的事情,需要搜索 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 并且 ItemControl 已准备就绪之后。我将在 Loaded 事件中执行此操作。

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

}

【讨论】:

  • 谢谢,正是我需要的。
猜你喜欢
  • 2015-03-25
  • 2012-12-22
  • 2014-08-03
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
  • 2011-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多