简体   繁体   English

DataGrid行添加事件

[英]DataGrid row added event

I know... this question was being asked a lot... but always with the same answer "put your logic in the viewmodel". 我知道……这个问题被问了很多……但总是有相同的答案“将您的逻辑放在视图模型中”。

But in this example I have to put the logic in the view because I have to measure the size of each datagrid in my view every time the row count of one of them is changing. 但是在此示例中,我必须将逻辑放在视图中,因为每当其中之一的行计数发生变化时,我都必须在视图中测量每个数据网格的大小。 The problem is... in my viewmodel I don´t have access to the datagrid, so I can´t measure anything. 问题是...在我的视图模型中,我无法访问数据网格,因此我无法进行任何测量。 And in my view I can´t get a response that the row count has changed. 在我看来,我无法获得行数已更改的响应。

Someone got an idea how I know in the view that a row was added or deleted in a datagrid? 有人知道我如何在数据网格中添加或删除行? It is a custom datagrid with a customtemplate btw. 它是带有自定义模板btw的自定义数据网格。 maybe that is going to help somehow? 也许那会有所帮助吗?

You have an ObservableCollection binded to the DataGrid , right? 您有一个绑定到DataGridObservableCollection ,对吗? And you have a ViewModel (which contains that ObservableCollection ) as the DataContext of the View . 并且您有一个ViewModel (其中包含ObservableCollection )作为ViewDataContext You may subscribe to the CollectionChanged event of the ObservableCollection within your view (you can access your ViewModel from your view, because it is the View.DataContext ). 您可以在视图内订阅ObservableCollectionCollectionChanged事件(您可以从视图访问ViewModel,因为它是View.DataContext )。

Eg 例如

(this.DataContext as ViewModel).YourCollection
    .CollectionChanged += (s, e) => { /* logic */ };

It slightly violates MVVM. 它稍微违反了MVVM。 If this is an absolutely custom control then you already receive the events from the ObservableCollection (because you need to update the UI) so you can handle this there. 如果这是绝对自定义控件,则您已经从ObservableCollection接收了事件(因为您需要更新UI),因此可以在那里进行处理。

Another approach I can think is to use some kind of Mediator pattern, eg Messenger in MVVMLight. 我可以想到的另一种方法是使用某种Mediator模式,例如MVVMLight中的Messenger

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM