我有ListBox
如下复选框,它绑定了它的数据SQL server database
。我想获得选定项目的价值当我运行这个但我得到这个错误:
无法将“System.Data.DataRowView”类型的对象转换为“System.Windows.Controls.CheckBox”类型。
这是代码:
<Window.Resources>
<DataTemplate x:Key="NameColumnTemplate">
<CheckBox Height="20" FontFamily="Arial" FontSize="14" Content="{Binding Path=PermissionDescription}" Tag="{Binding PermissionID}" HorizontalAlignment="Stretch" VerticalAlignment="Center" />
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox HorizontalAlignment="Stretch" Margin="12,12,136,21" Name="lstEmployees"
VerticalAlignment="Stretch" ItemsSource="{Binding Tables[0]}"
ItemTemplate="{StaticResource NameColumnTemplate}"
ScrollViewer.VerticalScrollBarVisibility="Auto" removed="{x:Null}"
BorderBrush="#FFAD7F30"
SelectionChanged="lst_SelectionChanged" CheckBox.Click="lst_SelectionChanged"/>
<Button Content="listbox" Height="23" HorizontalAlignment="Left" Margin="214,207,0,0" Name="btnShowSelectedItems" VerticalAlignment="Top" Width="75" Click="btnShowSelectedItems_Click" />
</Grid>
public Window2()
{
InitializeComponent();
// bind data
lstEmployees.DataContext = SelJobsCat();
}
private void btnShowSelectedItems_Click(object sender, RoutedEventArgs e)
{
foreach (CheckBox item in lstEmployees.Items)
{
if (item.IsChecked == true)
{
System.Windows.MessageBox.Show((item.Content + " is checked."));
}
}
}
private void lst_SelectionChanged(object sender, RoutedEventArgs e)
{
if (e.OriginalSource is CheckBox)
{
lstEmployees.SelectedItem = e.OriginalSource;
}
if (lstEmployees.SelectedItem == null) return;
Console.WriteLine(lstEmployees.SelectedIndex);
Console.WriteLine(((CheckBox)lstEmployees.SelectedItem).IsChecked);
}
请问我的错误在哪里,谢谢。