Datagrid ObservableCollection为一行wpf [英] Datagrid ObservableCollection for one row wpf

查看:140
本文介绍了Datagrid ObservableCollection为一行wpf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用itemsource = {Binding Model}填充一个datagrid。
这不行。似乎datagrid不明白如何显示这些属性。



一个容易但愚蠢的解决方法工作得很好:



在viewmodel中:

  Props = new ObservableCollection< MonitoringBinaryModel>(); 
_Model = new MonitoringBinaryModel(name);
Props.Add(_Model);

然后在xaml

  itemsource = {Binding Props} 

似乎愚蠢地创建一个可观察的集合,当它的唯一假设持有一个项目。有没有更好的方式来使任何类型的实例可观察?

解决方案

DataGrid旨在显示相同类型的对象的集合。收藏是必须的。如果您希望DataGrid显示您的模型的内容,您需要遵守前者的设计,可以使用ObservableCollection或实现一组接口,这样可以以收集方式检索您的viewmodel的属性。



我以前在Windows窗体时间里有一堆实现ITypedList接口的模型 - 这不是一个简单的练习说实话,所以如果我是你,我宁愿去方式:




  • 将模型包装到任何集合中 - 正如您所述

  • 用容器网格替换数据网格加上多个直接绑定,如下所示:

     < Grid> 
    < TextBlock Grid.Column =2Grid.Row =0Text =Prop1/>
    ...
    < TextBlock Grid.Column =2Grid.Row =1Text ={Binding Prop1}/>



I want to populate a datagrid with itemsource={Binding Model}. This is not working out. It seems as the datagrid does not understand how to display these properties.

An easy but silly workaround works great:

In viewmodel:

Props= new ObservableCollection<MonitoringBinaryModel>();
_Model = new MonitoringBinaryModel(name);
Props.Add(_Model);

Then in xaml

itemsource={Binding Props}

Seems silly to create an observablecollection when its only suppose to hold one item. Is there a better way to make any type of instance observable?

解决方案

DataGrid is designed to display a collection of objects of same type. Collection is a must. If you want DataGrid to show a content of your model, you need to obey former's design, by either using ObservableCollection or implementing a bunch of interfaces which would allow your viewmodel's properties to be retrieved in 'collection way'.

I used to have a bunch of models implementing ITypedList interface back in Windows Forms time - it wasn't a simple exercise to say the truth, so if I were you I'd rather go for either way:

  • Wrap model into any collection - exactly as you've stated
  • Replace data grid with container grid plus a number of direct bindings, like this:

    <Grid>
        <TextBlock Grid.Column="2" Grid.Row="0" Text="Prop1"/>
    ...
        <TextBlock Grid.Column="2" Grid.Row="1" Text="{Binding Prop1}"/>
    

这篇关于Datagrid ObservableCollection为一行wpf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆