【问题标题】:WPF binding - DataGrid.Items.CountWPF 绑定 - DataGrid.Items.Count
【发布时间】:2014-08-18 07:07:13
【问题描述】:

在我的视图中,有一个DataGrid和一个TextBox,绑定到DataGrid的Items.Count属性:

<DataGrid x:Name="dataGrid" ItemsSource="{Binding dataTable}"/>
<TextBox Text="{Binding Items.Count,ElementName=dataGrid,Mode=OneWay,StringFormat={}{0:#}}"/>

ViewModel 有一个属性(例如 ItemsCount),我想将它绑定到 DataGrid 的 Items.Count 属性,但不知道如何实现。

class ViewModel : INotifyPropertyChanged
{
    public DataTable dataTable {get;set;}
    public int ItemsCount {get;set;}
}

也许我也可以使用 DataGrid 绑定到的 DataTable 的 Rows.Count 属性,但是如何在 ViewModel 中绑定或链接这两个属性?

所以我基本上希望 ItemsCount 属性与 dataTable.Rows.Count 属性同步。

【问题讨论】:

  • 我假设您已将 DataGrid 的 ItemsSource 绑定到视图模型中的某种集合属性。为什么不将 TextBox 的 Text-property 绑定到该集合的 Count-Property?
  • 是的,它绑定到一个DataTable。添加或删除项目时,将 TextBox 绑定到 dataTable.Rows.Count 不会更新 TextBox。这也无助于更新 ViewModel 中的其他属性。我已经添加了 ViewModel 的源代码

标签: wpf xaml data-binding datagrid


【解决方案1】:

实现您的要求的常用方法是声明属性以将数据绑定到 UI 控件:

<DataGrid x:Name="dataGrid" ItemsSource="{Binding Items}" />
<TextBox Text="{Binding ItemsCount}" />

...

// You need to implement the INotifyPropertyChanged interface properly here

private ObservableCollection<YourDataType> items = new ObservableCollection<YourDataType>();
public ObservableCollection<YourDataType> Items
{
    get { return items; }
    set { items = value; NotifyPropertyChanged("Items"); NotifyPropertyChanged("ItemCount"); }
}

public string ItemCount
{
    get { Items.Count.ToString("{0:#}"); }
}

更新>>>

由于@Sivasubramanian 已将他自己的要求添加到您的问题中,如果您需要通过添加到您的收藏来专门更新项目计数,您可以手动调用NotifyPropertyChanged 方法:

Items.Add(new YourDataType());
NotifyPropertyChanged("ItemCount");

【讨论】:

  • 当我们将一个项目添加到“项目”集合中时,它不会在项目中触发 NotifyPropertyChange,在 ItemCount 中也是如此
  • 这是一个要求吗?即便如此,在这种情况下,您可以手动调用NotifyPropertyChanged("Items"); NotifyPropertyChanged("ItemCount");... 没问题。
  • 这个解决方案有什么问题,神秘的选民?想发表评论让你投反对票有什么意义,还是你会继续让它毫无意义?
  • 我投了反对票。 OP 说“ViewModel 有一个属性(例如 ItemsCount),我想将它绑定到 DataGrid 的 Items.Count 属性”
  • 真的...你投了反对票???对不起,但这是一个绝对可悲的理由。问题作者显然只是想查看那里的集合中的项目数。
猜你喜欢
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 2018-06-20
  • 2014-09-27
  • 2011-04-09
  • 2015-07-02
相关资源
最近更新 更多