2010-05-14 165 views
0

一直試圖弄清楚,我如何捕獲列表框中的事件。在模板中,我添加了參數IsChecked =「」,它啓動了我的方法。但是,問題是試圖捕獲方法中檢查的內容。 SelectedItem只返回當前選中的內容,而不是複選框。捕獲WPF Listbox複選框選擇

object selected = thelistbox.SelectedItem; 
DataRow row = ((DataRowView)selected).Row; 
string teststring = row.ItemArray[0].ToString(); // Doesn't return the checkbox! 

<ListBox IsSynchronizedWithCurrentItem="True" Name="thelistbox" ItemsSource="{Binding mybinding}"> 
    <ListBox.ItemTemplate> 
      <DataTemplate> 
        <StackPanel> 
          <CheckBox Content="{Binding personname}" Checked="CheckBox_Checked" Name="thecheckbox"/> 
         </StackPanel> 
       </DataTemplate> 
     </ListBox.ItemTemplate> 
</ListBox> 

回答

1

理想情況下,你應該綁定到器isChecked財產上的一行即

<CheckBox Content="{Binding personname}" IsChecked="{Binding IsPersonChecked}" Name="thecheckbox"/> 

其中「IsPersonChecked」在你的DataTable(或任何你綁定)列,就像「PERSONNAME」。然後,你可以閱讀無論是從您的DataRow變量直接檢查:

DataRow row = ((DataRowView)thelistbox.SelectedValue).Row; 
bool isPersonChecked = (bool) row["IsPersonChecked"]; 

如果數據集被輸入,要使用類型化的DataRow性能,效果顯着。

請注意,我使用了SelectedValue,而不是SelectedItem屬性。我相信SelectedItem實際上是ListBoxItem的一個實例。如果你想離開你的IsChecked,你可以使用它。然後,您必須考慮完整的模板層次結構來檢索CheckBox。例如:

bool isChecked = ((CheckBox)((StackPanel) ((ListBoxItem) thelistbox.SelectedItem).Content).Children[0]).IsChecked ?? false; 

凌亂。 (調試和不會調整層次來你就會得到我的代碼可能爲工作的。)

更好的方法是使用你的CheckBox_Checked處理程序的RoutedEventArgs:

private void CheckBox_Checked(object sender, RoutedEventArgs e) 
{ 
    CheckBox checkBox = (CheckBox) e.Source; 
    DataRow row = ((DataRowView) checkBox.DataContext).Row; 
    bool isChecked = checkBox.IsChecked ?? false; 
} 
+0

感謝這個!最後一種方法效果很好。想到使用你所描述的第二種方式,但是我的UI仍處於不斷變化的狀態。 – wonea 2010-05-17 09:11:16