如何将项目绑定到Listview

时间:2015-02-05 05:34:25

标签: c# wpf

我动态地将项目源绑定到Listview。项目本身是动态绑定的。这是我的代码..

    private void DisplayListView()
    {
        _MyControls = new ObservableCollection<MyControl>();
        _MyControls.Add(GetInnerelementsInfo());

    }
    private MyControl GetInnerelementsInfo()
    {
        records = new ObservableCollection<Record>();
        records.Add(new Record(new Property("FirstName", "ABC"), new Property("LastName", "DEF")));
        records.Add(new Record(new Property("FirstName", "GHI"), new Property("LastName", "JKL")));
        MyHeader = "Headername";

        var columns = records.First()
            .Properties
            .Select((x, i) => new { Name = x.Name, Index = i })
            .ToArray();

        foreach (var column in columns)
        {
            var binding = new Binding(string.Format("Properties[{0}].Value", column.Index));
            dataGrid.Columns.Add(new DataGridTextColumn() { Header = column.Name, Binding = binding });
        }
        MyControl c = new MyControl(MyHeader,records);
        return c;

    }

在我的XAML代码中我有

    <ListView x:Name="MyListView" ItemsSource="{Binding Path=_MyControls}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Expander Header="{Binding Path=MyHeader}">
                    <StackPanel Margin="10,4,0,0">
                        <DataGrid
x:Name="dataGrid"
AutoGenerateColumns="False"
ItemsSource="{Binding Path=records}"/>
                    </StackPanel>
                </Expander>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListView>

错误是&#39;数据网格在当前上下文中不存在&#39; 也有人能告诉我这是否是有效的方法..

由于 凯尔

1 个答案:

答案 0 :(得分:1)

由于您的数据网格在DataTemplate中,因此您无法使用x:Name属性直接在代码中访问它们。

相反,您可以尝试的只是在Xaml中触发该网格视图的加载事件

<DataGrid x:Name="dataGrid" Loaded="dataGrid_Loaded" />

并在后面的代码中使用以下代码

 private void dataGrid_Loaded(object sender, RoutedEventArgs e)
    {
        var mydataGrid = sender as DataGrid;
    }

现在您可以使用mydataGrid访问datagrid。