2010-05-14 127 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