【问题标题】:Unable to add new Row in DataGrid UI automatically无法在 DataGrid UI 中自动添加新行
【发布时间】:2016-02-17 02:31:35
【问题描述】:

我无法通过 UI 在我的 DataGrid 中添加新行。下面是我的代码。

<DataGrid CanUserAddRows="True" Name="dg"  ItemsSource="{Binding list}"  AutoGenerateColumns="False" >
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=.}" Header="Text"/>
        <DataGridTextColumn Binding="{Binding Length}" Header="Length"/>            
    </DataGrid.Columns>
</DataGrid>

list 是上面Binding 中的字符串列表。通常当我设置CanUserAddRows="True" 时,我能够在其他示例中自动在UI 上添加行.

我的财产如下:

public List<string> list { get; set; }

在显示DataGrid 之前,它已被初始化。所以不需要为这个属性实现INotifyPropertyChanged

有人能解释一下为什么DataGrid 会这样吗?如何实现期望的行为?

【问题讨论】:

标签: c# wpf xaml data-binding datagrid


【解决方案1】:

问题在于string 没有无参数构造函数,因此网格无法为空网格行创建新实例以允许用户添加新行。此外,网格不能“设置”“。”属性到字符串上。

一种选择是创建您自己的公开 Text 和 Length 属性的类:

public class StringMember : INotifyPropertyChanged
{
private string m_actualString;
public string Text
{
    get { return m_actualString; }
    set
    {
        m_actualString = value;
        //OnPropertyChanged("Text");
        //OnPropertyChanged("Length");
    }
}

public int Length { get { return Value.Length; } }

//public event PropertyChangedEventHandler PropertyChanged;        
//protected virtual void OnPropertyChanged(string propertyName = null)
//{
//    PropertyChangedEventHandler handler = PropertyChanged;
//    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
//}

}

然后,您的 XAML 将绑定到您的属性:

<DataGrid CanUserAddRows="True" Name="dg"  ItemsSource="{Binding list}"  AutoGenerateColumns="False" >
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Text}" Header="Text"/>
        <DataGridTextColumn Binding="{Binding Length}" Header="Length"/>            
    </DataGrid.Columns>
</DataGrid>

在这种情况下,您的“列表”属性将是 List&lt;StringMember&gt;ObservableCollection&lt;StringMember&gt; 而不是 string

【讨论】:

  • 那么如何处理我的模型类没有默认构造函数定义的情况呢?可选参数可以吗?
  • 那么你知道我不需要创建派生/包装类的任何解决方法吗?
猜你喜欢
  • 2010-10-15
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2015-04-06
  • 2011-08-26
  • 2012-08-06
相关资源
最近更新 更多