简体   繁体   中英

C# wpf proper way to bind DisplayIndex property of datagrid column

I have bound the displayindex of my column to an integer variable (DisplayIndex_Name) in my datacontext.

XAML code:

<DataGridTextColumn Header="Name" DisplayIndex="{Binding Path=DisplayIndex_Name}" />

The column position in my datagrid is now equal to the value stored in DisplayIndex_Name.

(If I set this to 0, this will show up as my first column)

The problem is when I have multiple columns, If I change the displayIndex of 1 of them, all other displayindexes get updated since every column must have a unique value.

This now means that the displayindex != the integer value to which it should be bound..

Any idea how I can update my variables in my datacontext to the exact value of the displayindex?

You're not setting Mode=TwoWay in your binding and thus when you move columns around they don't update the backend. I think adding that will solve the issue.

In your case it's just wrong index, in my case there may be crash. I did a lot of investigation on this to find out the root cause and work around, just put here in case anyone really need TwoWay bind in display index (which is my case).

Root cause:

When we set several display index data grid will apply them one by one. And every time data grid applied one index, it need modify other indexes to make sure all the indexes together are valid, and two way binding will give this value back to viewmodel, which will end up with changed the display order we want, or even get index out of range.

Work around:

There are some problems with the last work around, I'm working on a customer binding with mode OneTime and OneWayToSource, which will solve this. Will update here after done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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