隐藏datagrid自动添加的列

时间:2012-09-26 08:38:06

标签: wpf xaml wpfdatagrid

在xaml下面,datagrid在Image列之前和price列之后给了我两个额外的列。我该如何禁用它?

<DataGrid Name="dgProductList" AutoGenerateColumns="False" FontSize="18" 
                                  ScrollViewer.CanContentScroll="False"      
                                  ScrollViewer.VerticalScrollBarVisibility="Auto" 
                                  ScrollViewer.HorizontalScrollBarVisibility="Auto">
                            <DataGrid.Columns>
                                <DataGridTemplateColumn Header="Image">
                                    <DataGridTemplateColumn.CellTemplate>
                                        <DataTemplate>
                                            <Image Height="10" Width="10" Source="{Binding Picture}" Stretch="Uniform"></Image>
                                        </DataTemplate>
                                    </DataGridTemplateColumn.CellTemplate>
                                </DataGridTemplateColumn>
                                <DataGridTextColumn Binding="{Binding Name}" Header="Item" />
                                <DataGridTextColumn Header="Qty" />
                                <DataGridTextColumn Binding="{Binding Price}" Header="Price" />
                            </DataGrid.Columns>
                        </DataGrid>

谢谢。

2 个答案:

答案 0 :(得分:3)

在DataGrid中添加itemssource绑定:

<DataGrid Name="dgProductList" AutoGenerateColumns="False" FontSize="18"
                              ScrollViewer.CanContentScroll="False"
                              ScrollViewer.VerticalScrollBarVisibility="Auto"
                              ScrollViewer.HorizontalScrollBarVisibility="Auto"
          ItemsSource="{Binding Products}" MouseDoubleClick="dgProductList_MouseDoubleClick">

Codebehind:

public class Product : NotificationObject
{
    public string Name { get; set; }
}

public IList<Product> Products { get; set; }

public MainWindow()
{
    Products = new ObservableCollection<Product>
    {
        new Product {Name = "test1"},
        new Product {Name = "test2"},
    };

    DataContext = this;

    InitializeComponent();
}

private void dgProductList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    Products.Add(new Product { Name = "test x" });
}

答案 1 :(得分:1)

如果我只是复制并粘贴您的xaml,则没有额外的列。也许codebehind文件中有一些代码可以创建列?