簡體   English   中英

從DataGrid的DataGridTemplateColumn獲取Checkbox值

[英]Get Checkbox Value From DataGridTemplateColumn of DataGrid

我有這個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
    }
}

我的代碼錯了?

既然你是在循環的Items集合這是你ItemsSource 為什么不在你的班級中擁有bool property並從那里獲取它。

假如ItemSource是List<Person> ,那么創建一個bool屬性,在類PersonIsManager並將其與你的checkBox綁定,如下所示 -

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

現在你可以循環遍歷Items以獲得這樣的值 -

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM