开发者

WPF: DataGrid Find and Replace

开发者 https://www.devze.com 2023-01-10 06:50 出处:网络
I\'m using a DataGrid to display the values of specific properties of a collection of objects. I\'ve implemented search and cell highlighting through a similar method to the one on Tomer Shamam\'s blo

I'm using a DataGrid to display the values of specific properties of a collection of objects. I've implemented search and cell highlighting through a similar method to the one on Tomer Shamam's blog.

However, I now need to implement 'Find/Replace' type functionality. I p开发者_如何学编程resumed I would be able to iterate through the DataGrid's cells to perform highlighting and replacements, but there doesn't seem to be a simple way to do this.

Any ideas?


I think you perhaps have a wrong mindset in this scenario, perhaps you are coming from WinForms to the WPF world...

In WPF DataGrid you basically never manipulate data via the DataGrid, you always work on the DataSource directly. As to "there doesn't seem to be a simple way to do this" - you are right. It's going to be more difficult than it should.

If I was to implement a Find/Replace feature - each click would first highlight the next occurence then I can either choose to skip/find_next or replace - then this is how I would do it:

1) We need to know our current position - DataGrid.CurrentItem gives the current (data source) object;
2) Now we perform a search on the data source to find the next occurence starting from the current objects location (eg. var indx = List<object>.FindIndex(...) followed by var nextItem = List<object>[indx]);
3) Then we need to scroll the DataGrid to the found object and bring the DataGridRow into view - DataGrid.ScrollIntoView(nextItem); (you might need to do DataGrid.UpdateLayout() before the call, there appears to be some quirks with the .NET 4 built-in DataGrid in my experience);
4) You should already know how to highlight a cell...;
5) Wait for user input, either skip or replace;
6) If we replace then we can either use DataGrid.CurrentItem or the nextItem variable and replace some value with new value. Depending on how you have set up your DataGrid, you might need to do some Refresh()/UpdateLayout() call or a BindingOperations.GetBindingExpression(...).UpdateTarget() call to update the DataGrid;
7) Finally go back to step 1 and repeat;

0

精彩评论

暂无评论...
验证码 换一张
取 消