4

私はこのXAMLを持っています

<DataGrid Name="grdData" ... >
   <DataGrid.Columns>
      <DataGridTemplateColumn Header="Something">
         <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
               <CheckBox Name="chb" />
            </DataTemplate>
         </DataGridTemplateColumn.CellTemplate>
       </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

このコードを試して Checked State を取得します

for( int i = 0 ; i < grdData.Items.Count ; i++ )
{
    DataGridRow row = ( DataGridRow )grdData.ItemContainerGenerator.ContainerFromIndex( i );
    var cellContent = grdData.Columns[ 1 ].GetCellContent( row ) as CheckBox;
    if( cellContent != null && cellContent.IsChecked == true )
    {
       //some code
    }
}

私のコードは間違っていますか?

4

1 に答える 1

5

ItemsコレクションであるItemsSource. bool propertyクラス自体にを持ち、そこから取得しないのはなぜですか。

ItemSource が である場合、クラスでList<Person>bool プロパティを作成し、次のように checkBox にバインドします -IsManagerPerson

<CheckBox IsChecked="{Binding IsManager}"/>

これで、アイテムをループして、次のような値を取得できます-

foreach(Person p in grdData.ItemsSource)
{
   bool isChecked = p.IsManager; // Tells whether checkBox is checked or not
}

編集

プロパティを作成できない場合は、VisualTreeHelperメソッドを使用してコントロールを見つけることをお勧めします。このメソッドを使用して子を見つけます (ジェネリックなので、これをいくつかのユーティリティ クラスに配置して使用することができます) -

public static T FindChild<T>(DependencyObject parent, string childName)
           where T : DependencyObject
{
   // Confirm parent is valid.  
   if (parent == null) return null;

   T foundChild = null;

   int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
   for (int i = 0; i < childrenCount; i++)
   {
      var child = VisualTreeHelper.GetChild(parent, i);
      // If the child is not of the request child type child 
      T childType = child as T;
      if (childType == null)
      {
          // recursively drill down the tree 
          foundChild = FindChild<T>(child, childName);

          // If the child is found, break so we do not overwrite the found child.  
          if (foundChild != null) break;
      }
      else if (!string.IsNullOrEmpty(childName))
      {
          var frameworkElement = child as FrameworkElement;
          // If the child's name is set for search 
          if (frameworkElement != null && frameworkElement.Name == childName)
          {
             // if the child's name is of the request name 
             foundChild = (T)child;
             break;
          }
      }
      else
      {
          // child element found. 
          foundChild = (T)child;
          break;
       }
   }
   return foundChild;
}

上記のメソッドを使用して、チェックボックスの状態を取得します-

for (int i = 0; i < grd.Items.Count; i++)
{
   DataGridRow row = (DataGridRow)grd.ItemContainerGenerator.ContainerFromIndex(i);
   CheckBox checkBox = FindChild<CheckBox>(row, "chb");
   if( checkBox != null && checkBox.IsChecked == true )
   {
       //some code
   }
}
于 2012-10-14T08:03:44.390 に答える