繁体   English   中英

如何使用MVVM从DataGrid获取SelectedItems

[英]How to Get SelectedItems From DataGrid Using MVVM

我正在使用C#构建WPF应用程序,并且在我的应用程序中使用了MVVM体系结构 我使用DataTemplate在telerik gridview中创建了一个CheckBox列 我正在使用一个集合来绑定GridView中的数据。

当在网格上选中CheckBox 时,如何找到在该Collection中选择的DataItem特定行号

在这里我在网格上创建CheckBox的代码是:

<telerik:GridViewDataColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
                                <CheckBox Name="StockCheckBox" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type telerik:GridViewRow}}, Path=IsSelected}" />
                             </StackPanel>
                        </DataTemplate>
                    </telerik:GridViewDataColumn.CellTemplate>

我的收藏是

   foreach (var AvailableStock in AvailableStocks)// In this **AvailableStocks**(IEnumurable Collection) I got all the datas in the Gridview 
        //In this collection How can i know that the particular RowItem is selected in that gridview by CheckBox
      {
          if (SelectedStock != null)
          {
             this.SelectedStocks.Add(AvailableStock );

             this.RaisePropertyChanged(Member.Of(() => AvailableStocks));
          }
      }

任何人请告诉我有关此的一些建议我该如何实现? 我如何识别已选择的特定行

提前致谢。

我建议使用MVVM方法,并使用绑定来获取所选项目。 不幸的是,DataGrid没有为选定的项目提供DependencyProperty,但是您可以提供自己的。 从DataGrid派生一个类,为SelectedItems注册一个依赖项属性,并重写SelectionChanged事件以更新您的依赖项属性。 然后,您可以使用Binding通知您的ViewModel所选项目。

码:

public class CustomDataGrid : DataGrid
{
    public static readonly DependencyProperty CustomSelectedItemsProperty = DependencyProperty.Register(
        "CustomSelectedItems", typeof (List<object>), typeof (CustomDataGrid), 
        new PropertyMetadata(new List<object>()));

    public List<object> CustomSelectedItems
    {
        get { return (List<object>) GetValue(CustomSelectedItemsProperty); }
        set { SetValue(CustomSelectedItemsProperty, value);}
    }

    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        foreach(var item in e.AddedItems)
            CustomSelectedItems.Add(item);
        foreach (var item in e.RemovedItems)
            CustomSelectedItems.Remove(item);
        base.OnSelectionChanged(e);
    }
}

XAML:

<Grid>
    <Ctrl:CustomDataGrid CustomSelectedItems="{Binding MySelectedItems}"/>
</Grid>

暂无
暂无

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

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