【问题标题】:Add blank editable row to Datagrid but not to collection/list将空白可编辑行添加到 Datagrid 但不添加到集合/列表
【发布时间】:2014-11-17 04:53:34
【问题描述】:

如何在 Datagrid 中有一个空白行,但它没有添加到集合(模型)中?这应该更像是一个占位符行,当正确填写后,它会被添加到集合/模型中,并显示一个空白行。

经过研究,很多人建议只在集合中插入一个空白对象(这不是我真正想做的)或将集合包装在我自己的包装类中。有没有使用模板来做到这一点?

编辑:如果有人熟悉 GNUCash,那就是我想要的......

MainWindow.xaml

<Window x:Class="LogbookApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:local="clr-namespace:LogbookApp">
    <DockPanel>
        <Menu Height="23" HorizontalAlignment="Stretch" Name="menu1" VerticalAlignment="Top" DockPanel.Dock="Top">
            <MenuItem Header="_File" />
            <MenuItem Header="_Edit" />
        </Menu>
        <ToolBar Height="26" HorizontalAlignment="Stretch" Name="toolBar1" VerticalAlignment="Top" DockPanel.Dock="Top">
        </ToolBar>
        <DataGrid ItemsSource="{Binding Entries}" CanUserAddRows="True" AutoGenerateColumns="False" HeadersVisibility="Column">
           <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}"/>
            </DataGrid.Columns>
        </DataGrid>
    </DockPanel>
</Window>

我正在绑定到 CollectionViewSource,但我也尝试过使用 ObservableCollection 类型。

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    设置 CanUserAddRows="True" 将为您提供占位符

    <DataGrid CanUserAddRows="True">
    

    【讨论】:

    • 为我工作.. 你能分享你的数据网格 xaml 和你绑定到的 ItemsSource 类型
    【解决方案2】:

    已解决...

    在这种情况下,类 LogbookEntry 需要有一个空的构造函数,即。

    public class LogbookEntry ()
    

    【讨论】: