【问题标题】:set ItemTemplate for specific column of DataGrid为 DataGrid 的特定列设置 ItemTemplate
【发布时间】:2013-03-12 19:33:54
【问题描述】:

我有一个 WPF DataGrid,它绑定到 List<Person> people

public class Person
{
    public string Name{get;set;}
    public string LastName{get;set;}
    public string Address{get;set;}
    public int Age{get;set;}
}

public void ShowPeople()
{
     myDataGrid.ItemsSource = people;
}

它显示一切正常,但我想在TextBox 中显示Address DataGrid

我将 XAML 代码更改为:

   <DataGrid x:Name="myDataGrid">
        <DataGridTemplateColumn Header="Address">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Address}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid>

这不起作用。它给了我一个错误。

在使用 ItemsSource 之前,Items 集合必须为空。

请帮忙。 谢谢,

【问题讨论】:

    标签: wpf wpf-controls wpfdatagrid


    【解决方案1】:

    您的 XAML 中缺少 Columns 属性:

    <DataGrid x:Name="myDataGrid">
        <DataGrid.Columns> <-- This is missing in your code!
            <DataGridTemplateColumn Header="Address">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding Path=Address}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    

    【讨论】:

    • 在代码后面做什么?创建整个 DataGrid 而不是使用 XAML?
    • 将 ItemTemplate 设置为列。
    • 我不知道,抱歉。也许你应该发布一个新问题。其他人可能知道:)
    猜你喜欢
    • 2011-03-17
    • 2019-06-05
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 2011-09-01
    • 2011-10-15
    • 1970-01-01
    相关资源
    最近更新 更多