2011-10-20 47 views
0

我有兩個自定義控件。首先我有一個複選框定製控制,myCheckboxControl,(下面簡單求XAML)以編程方式檢查複選框(usercontrol)與DataGrids(usercontrol)SelectedItem/Row WPF XAML

<UserControl x:Class="UserControls.myCheckboxControl"><Grid> 
     <CheckBox x:Name="chkboxList" HorizontalAlignment="Center" Checked="chkboxList_Checked"> 
</Grid></UserControl> 

我也有AA定製數據網格控制(下面簡化XAML)包含在一個DataTemplate

<UserControlx:Class="UserControls.myDataGridControl"><DataGrid x:Name="dgMyGrid> 
<DataGrid.Columns> 
      <DataGridTemplateColumn x:Name="tempCol" Header="Checkbox(L)"> 
       <DataGridTemplateColumn.CellTemplate> 
        <DataTemplate> 
         <localControls:myCheckboxControl x:Name="controlList"/> 
        </DataTemplate> 
       </DataGridTemplateColumn.CellTemplate> 
      </DataGridTemplateColumn> 
     </DataGrid.Columns> 
    </DataGrid> 

複選框控制然後我在我的MainWindow中有DataGrid(myDataGridControl)。

我的問題是,我在MainWindow上有一個按鈕。當該按鈕被點擊時,我需要它也檢查myCheckboxControl中的複選框。我可以得到DataGrid的SelectedItem,但不知道如何讓我的2級深層複選框被檢查。

在此先感謝。

回答

0

正如您已經知道該複選框是託管在datagrid行上的用戶控件的後代。

所以你將不得不通過使用介體屬性myCheckboxControl來解決這兩個級別的界限,以保存CheckBox.IsChecked。你可以在myCheckboxControl中引入一個新的依賴項屬性,比如IsCheckBoxChecked這個用法在進一步的討論中。

我正在使用另一個屬性Tag,它是一個佔位符,用於添加任何額外的信息,可能需要添加一個框架元素。

<UserControl x:Class="UserControls.myCheckboxControl"> 
     <Grid> 
      <CheckBox x:Name="chkboxList" 
         HorizontalAlignment="Center" 
         IsChecked="{Binding 
            Tag, 
            RelativeSource={RelativeSource 
             AncestorType={x:Type UserControl}} 
            Mode=TwoWay}"> 
     </Grid> 
    </UserControl> 


    <DataGridTemplateColumn.CellTemplate> 
     <DataTemplate> 
      <localControls:myCheckboxControl 
         Tag="{Binding 
           IsSelected, 
           Mode=TwoWay, 
           RelativeSource={RelativeSource 
            AncestorType={x:Type DataGridRow}}}" 
         x:Name="controlList"/> 
     </DataTemplate> 
    </DataGridTemplateColumn.CellTemplate> 

因此,當你以編程方式選擇數據網格行,那麼相應的該行復選框將被檢查。此外,當您選中複選框時,該行將被選中,反之亦然。

現在,如果您不想在選中複選框時進行選擇,則必須在行項目級別引入基於INotifyPropertyChanged的可通知屬性。

E.g.如果您將員工列表綁定到數據網格,則每個員工類必須具有名爲「IsSelected」的可設置屬性。這個類必須實現INotifyPropertyChanged接口,並且應該從setter提出屬性更改通知IsSelected屬性。

在結合這種情況下改變這種...

  <localControls:myCheckboxControl 
         Tag="{Binding 
           IsSelected, 
           Mode=TwoWay}" 
         x:Name="controlList"/> 

讓我知道,如果這有助於。