wpf 为 DataGrid 的特定列设置 ItemTemplate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15578907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:16:06  来源:igfitidea点击:

set ItemTemplate for specific column of DataGrid

wpfwpf-controlswpfdatagrid

提问by wpf_starter

I have a WPF DataGridand it is bound to List<Person> people.

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

It shows everything fine, but I want to show Addressin TextBoxinside the DataGrid.

这表明一切正常,但我想显示AddressTextBox里面DataGrid

I changed XAML code to this:

我将 XAML 代码更改为:

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

this is not working. It is giving me an error.

这是行不通的。它给了我一个错误。

Items collection must be empty before using ItemsSource.

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

Please help. Thanks,

请帮忙。谢谢,

回答by Peter Hansen

You are missing the Columnsproperty in your XAML:

您缺少ColumnsXAML 中的属性:

<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>