WPF绑定-DataGrid.Items.Count

WPF绑定-DataGrid.Items.Count,wpf,xaml,data-binding,datagrid,Wpf,Xaml,Data Binding,Datagrid,在我看来,有一个DataGrid和一个TextBox,它们绑定到DataGrid的Items。Count属性: <DataGrid x:Name="dataGrid" ItemsSource="{Binding dataTable}"/> <TextBox Text="{Binding Items.Count,ElementName=dataGrid,Mode=OneWay,StringFormat={}{0:#}}"/> 也许我也可以使用DataGrid绑定到的Dat

在我看来,有一个DataGrid和一个TextBox,它们绑定到DataGrid的Items。Count属性:

<DataGrid x:Name="dataGrid" ItemsSource="{Binding dataTable}"/>
<TextBox Text="{Binding Items.Count,ElementName=dataGrid,Mode=OneWay,StringFormat={}{0:#}}"/>
也许我也可以使用DataGrid绑定到的DataTable的Rows.Count属性,但是如何在ViewModel中绑定或链接这两个属性呢


因此,我基本上希望ItemsCount属性与dataTable.Rows.Count属性同步。

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

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

当我们向“items”集合中添加一个项时,它不会在items和itemcount中触发NotifyPropertyChange,这是一个要求吗?即使如此,在这种情况下,您也可以手动调用
NotifyPropertyChanged(“Items”);NotifyPropertyChanged(“ItemCount”)。。。没问题,这个解决方案有什么问题吗?你想发表评论让你的否决票有一些意义,还是你会继续让它变得毫无意义?我投了否决票。OP说“ViewModel有一个属性(例如ItemsCount),我想绑定到DataGrid的Items.Count属性”真的。。。你投了反对票???对不起,但这绝对是个可悲的理由。问题作者显然只是想查看这些集合中的项数。我假设您已将DataGrid的ItemsSource绑定到viewmodel中的某种集合属性。为什么不将TextBox的Text属性绑定到该集合的Count属性?是的,它绑定到DataTable。添加或删除项目时,将文本框绑定到dataTable.Rows.Count不会更新文本框。此外,这也无助于更新ViewModel中的其他属性。我已经添加了ViewModel的源
<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:#}"); }
}
Items.Add(new YourDataType());
NotifyPropertyChanged("ItemCount");