【发布时间】:2015-04-12 23:47:00
【问题描述】:
我正在为 WPF 应用程序实现 MVVM。 ViewModel 的创建方式如下:
- ViewModel:所有 ViewModel 覆盖的基类
- MainTemplateViewModel:“Masterpage”ViewModel,其中包含 ViewModel 属性
Current,其中包含要显示的 ViewModel - CustomerOverviewViewModel:可以放在
MainTemplateViewModel.Current中的视图示例
CustomerGridViewModel 包含 Telerik GridView。我想在 MainTemplateViewModel 的标题中显示项目数。 GridView.Items.Count 属性实现了INotifyPropertyChanged,所以我想将此属性绑定到ViewModel.RowCount(因为 CustomerGridViewModel 不知道它是 MainTemplateViewModel 的一部分,因此不能直接绑定到 TextBlock)。我可以反过来使用ViewModel.NumberOfRecords 在标题中显示金额。
如何将 Count 属性绑定到 ViewModel 中的属性?
编辑
我会更详细地描述这个问题:
网格中显示的对象列表是来自 ViewModel 的绑定:
<telerik:RadGridView x:Name="CustomerGrid" ItemsSource="{Binding CustomerViewModels}">
</telerik:RadGridView>
当过滤内存中的网格时,Telerik 网格会自动更改GridView.Items.Count 属性(这并不意味着更改了原始列表计数!)。因此,如果我可以将此属性绑定到 ViewModel 类中的属性,这将解决问题。
ViewModel.cs
public class ViewModel : INotifyPropertyChanged
{
private int numberOfRecords;
public int NumberOfRecords
{
get { return numberOfRecords; }
set { numberOfRecords = value; OnPropertyChanged(); }
}
}
MainTemplateViewModel.cs
public class MainTemplateViewModel : ViewModel
{
private ViewModel current = new MainOverviewViewModel();
public ViewModel Current
{
get { return current; }
set
{
if (current != value)
{
current = value; OnPropertyChanged();
}
}
}
}
CustomerOverview.xaml.cs
public partial class CustomerOverview : UserControl
{
public CustomerOverview()
{
InitializeComponent();
this.CustomerGrid.Items.CollectionChanged += ItemsCollectionChanged;
this.CustomerGrid.Loaded += CustomerGrid_Loaded;
}
void CustomerGrid_Loaded(object sender, RoutedEventArgs e)
{
/* METHOD 1 PROBLEM: the field to bind to in the MainTemplate is out of scope and accessing a view is not MVVM */
var binding = new Binding();
binding.Path = new PropertyPath("Items.Count");
binding.Source = CustomerGrid;
((MainWindow)this.ParentOfType<MainWindow>()).NumberOfRecords.SetBinding(TextBlock.TextProperty, binding);
}
void ItemsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
/* METHOD 2 PROBLEM: codebehind code should be in viewmodel */
((CustomerOverviewViewModel)this.DataContext).NumberOfRecords = CustomerGrid.Items.Count;
}
}
【问题讨论】:
标签: c# wpf mvvm telerik-grid