How to Bind CurrentCell in WPF datagrid using MVVM pattern

前端 未结 1 585
长发绾君心
长发绾君心 2021-01-06 02:44

I\'m learning WPF MVVM pattern. I\'m stuck in Binding CurrentCell of datagrid. Basically I need the row index and column index of current cell.

相关标签:
1条回答
  • 2021-01-06 03:10

    After having a quick poke-around I've noticed a very simple solution to your problem.

    First of all there's two problems rather then one here. You cannot bind a CellInfo of a type DataGridCell, it needs to be DataGridCellInfo as xaml cannot convert it on its own.

    Secondly in your xaml you will need to add Mode=OneWayToSource or Mode=TwoWay to your CellInfo binding.

    Here is a rough example semi-related to your original code

    XAML

    <DataGrid AutoGenerateColumns="True"
              SelectionUnit="Cell"
              SelectionMode="Single"
              Height="250" Width="525" 
              ItemsSource="{Binding Results}"
              CurrentCell="{Binding CellInfo, Mode=OneWayToSource}"/>
    

    VM

    private DataGridCellInfo _cellInfo;
    public DataGridCellInfo CellInfo
    {
        get { return _cellInfo; }
        set
        {
            _cellInfo = value;
            OnPropertyChanged("CellInfo");
            MessageBox.Show(string.Format("Column: {0}",
                            _cellInfo.Column.DisplayIndex != null ? _cellInfo.Column.DisplayIndex.ToString() : "Index out of range!"));
        }
    }
    

    Just a small tip - if you debug your app and look at the Output window it actually tells you if there is any troubles with your bindings.

    Hope this helps!

    K.

    0 讨论(0)
提交回复
热议问题