2016-04-09 59 views
0

私はDataGridにテキストボックスを持っています。データはデータベースから取得しています。私はこれらのテキストボックスの値を持つ10行があると仮定します。一度この行をクリックすると、この選択された行インデックスを取得できます。私の目標は、一度テキストボックスの値が変更されると、私はそれがどの行(どの値)であるかを検出し、この値に基づいて計算を行い、同じ行の別のフィールドを表示する必要があるかどうかです。だから私は、どの行がヒットするのかを知る立場にいる。 `私は次の宣言とデータグリッドを使用しています:WPF - DataGridで選択された行インデックスを取得するには?

<dg:DataGrid Name="dgBudgetAllocation" CanUserDeleteRows="False" CanUserAddRows="False" CanUserSortColumns="True" 
         IsSynchronizedWithCurrentItem="True" MaxHeight="400" RowHeight="70" SelectionUnit="Cell" SelectedValue="" SelectionMode="Single" 
       AutoGenerateColumns="False" GridLinesVisibility="None" HeadersVisibility="Column" PreviewMouseDown="DgBudgetAllocation_OnPreviewMouseDown" SelectedCellsChanged="DgBudgetAllocation_OnSelectedCellsChanged" MouseDown="DgBudgetAllocation_OnMouseDown" PreviewMouseUp="DgBudgetAllocation_OnPreviewMouseUp" PreviewKeyDown="DgBudgetAllocation_OnPreviewKeyDown" HorizontalAlignment="Left"> 


         <dg:DataGridTemplateColumn Header="Budget Type" SortMemberPath="BUDGETYPE" 
             MinWidth="50" HeaderStyle="{DynamicResource dgHeaderLeftJust}" CellStyle="{DynamicResource dgColumnRightJust}"> 
       <dg:DataGridTemplateColumn.CellTemplate> 
        <DataTemplate> 
         <TextBlock Text="{Binding BUDGETYPE}" HorizontalAlignment="left" VerticalAlignment="Top" Margin="0,0,3,0" /> 
        </DataTemplate> 
       </dg:DataGridTemplateColumn.CellTemplate> 

      </dg:DataGridTemplateColumn> 

私は、様々な人の提案に基づいて、次のスニペットを試してみました。選択したインデックスを取得するすべてのために-1です。

DataRowView drv = (DataRowView)dgBudgetAllocation.SelectedItem; 
       object item = dgBudgetAllocation.SelectedItem; 
       string ID = (dgBudgetAllocation.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text; 
       DataGrid row1 = (DataGrid)dgBudgetAllocation.SelectedItems[1]; 
       var row = dgBudgetAllocation.SelectedItems[0]; 

何も問題ありません。 さらに進めてください。

答えて

2

選択変更イベント(SelectionChanged = "ItemsView_OnSelectionChanged")をサブスクライブし、必要なものすべてを取得するためにハンドラを使用します。ビヘイビア(およびMVVM)でそれを行うことも、ハンドラをコードの中に入れることもできます。

ハンドラのコード例

private void ItemsView_OnSelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     var dg = sender as DataGrid; 
     if (dg == null) return; 
     var index = dg.SelectedIndex; 
     //here we get the actual row at selected index 
     DataGridRow row = dg.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow; 

     //here we get the actual data item behind the selected row 
     var item = dg.ItemContainerGenerator.ItemFromContainer(row); 

    } 

あなたはより多くの説明が必要なら、私に教えてください。よろしくです。 よろしくお願いします。

+0

私の作品です。どうもありがとうございます。あなたは私の多くの時間を救った。もう一度ありがとう。 – Santhosh

関連する問題