2012-02-13 8 views
1

私はC#を使用してWPFアプリケーションを構築していますが、MVVMアーキテクチャをアプリケーションに使用しています。 DataTemplateを使用して、チェックボックス列を作成しました。私はコレクションを使用してGridViewのデータをバインドしています。MVVMを使用してDataGridからSelectedItemsを取得する方法

特定の行番号のDataItemがそのコレクションで選択されているグリッドでチェックボックスがオンになっているとどうなりますか?

ここではグリッド上のチェックボックスを作成するための私のコードは次のとおりです。

<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)); 
      } 
     } 

誰もがどのように私はこれを達成することができます私は、この上でいくつかの提案を教えてください? 特定の行が選択されたことをどのようにして特定できますか

ありがとうございました。

+0

あなたはすべての3つの質問や答えが必要なのですか...? 'MVVMを使用してDataGridからSelectedItemsを取得する方法' 'CheckBoxをグリッドでチェックすると、そのコレクションで選択されたDataItemの特定の行番号を見つけることができます。' '特定の行がどのように選択されているかを確認するにはどうすればいいですか ' –

+0

jberger、はい私はそれが必要です。 – SuryaKavitha

+1

行番号を知る必要がありますか、または行がバインドされているコレクション内のオブジェクトを知るだけでよいですか? –

答えて

0

MVVMアプローチを使用し、選択したアイテムを取得するためにバインディングを使用することをお勧めします。残念ながら、DataGridは選択したアイテムにDependencyPropertyを提供しませんが、独自のアイテムを提供できます。 DataGridからクラスを派生させ、SelectedItemsの依存関係プロパティを登録し、SelectionChangedイベントをオーバーライドして依存関係プロパティを更新します。次に、バインディングを使用して、選択した項目を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> 
関連する問題