在grid-model中将gridview选定的行绑定到DataTable

时间:2018-01-12 04:04:43

标签: c# mvvm devexpress

我在视图中有一个gridview,一个类型的属性是viewmodel中的DataTable。 我想在gridview行单击或聚焦时将gridview中的选定行绑定到视图模型中的属性。

1 个答案:

答案 0 :(得分:0)

查看Tutorials

// Model
public class Model{
    // ...
}
// View Model
public class ViewModel {
    public ViewModel(){
        Entities = <... load entities here...>;
    }
    public IList<Model> Entities {
        get;
        private set;
    }
    public virtual Model SelectedEntity {
        get;
        set;
    }
    protected void OnSelectedEntityChanged() {
        // do something
    }
}

// View
using DevExpress.XtraGrid.Views.Base;
...
var fluent = mvvmContext.OfType<ViewModel>();
// bind the datasource
fluent.SetBinding(gridControl1, gControl => gControl.DataSource, x => x.Entities);
// bind the FocusedRowObject
fluent.WithEvent<ColumnView, FocusedRowObjectChangedEventArgs>(gridView1, "FocusedRowObjectChanged")
    .SetBinding(x => x.SelectedEntity,
        (args) => args.Row as Model,
        (gView, entity) => gView.FocusedRowHandle = gView.FindRow(entity));

PS。您可以针对任何特定的数据层调整上面的代码(例如DataTable,但我相信简单的DTO列表是一个更好和可维护的选择)。