ListBox SelectedItem始终为null

时间:2016-07-07 08:30:43

标签: c# wpf xaml listbox

当我点击ListBox中的某个项目时,它总是返回null。当然我的ListBox已经填满:-)
我的XAML代码:

Item_Name   Price   UniqueDays  AvgSalesPerDay
Potatoes    2.80    1           9
Potatoes    2.90    2           27
Potatoes    3.00    2           13
Potatoes    3.10    1           8
Potatoes    3.20    1           2

我的C#代码:

<Window x:Class="WpfTimeClock.AdminWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfTimeClock"
    mc:Ignorable="d"
    ResizeMode="CanMinimize"
    Title="AdminWindow" Height="527" Width="750">
<Grid>
    <ListBox x:Name="listBoxUsers" HorizontalAlignment="Left" Height="250" VerticalAlignment="Top" Width="200" Margin="10,10,0,0"/>
</Grid>
</Window>

当我点击它时,我的TimeClockRepository<User> repUser = new TimeClockRepository<User>(); public AdminWindow() { InitializeComponent(); Loaded += AdminWindow_Loaded; listBoxUsers.PreviewMouseLeftButtonDown += ListBoxUsers_PreviewMouseLeftButtonDown; } private void ListBoxUsers_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var item = sender as ListBoxItem; if (item != null && item.IsSelected) { // why is sender always null?? } } private void AdminWindow_Loaded(object sender, RoutedEventArgs e) { listBoxUsers.ItemsSource = repUser.Get().ToList(); listBoxUsers.DisplayMemberPath = "UserName"; } 项始终为空。问题是什么?谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

您应该处理ListViewItem,而不是ListBox。只需在ListViewItem中为ListView.ItemContainerStyle创建处理程序:

XAML:

<ListView ItemsSource={Binding YourItems}>
    <ListView.View>
        <GridView>
            <!-- Declare a GridViewColumn for each property -->
        </GridView>
    </ListView.View>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

代码隐藏:

private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var item = sender as ListViewItem;
    if (item != null && item.IsSelected)
    {
        //Do your actions
    }
}

答案 1 :(得分:1)

您应该使用 SelectionChanged 事件。

this.listBoxUsers.SelectionChanged += ListBoxUsers_SelectionChanged;

private void ListBoxUsers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // do your things with listBoxUsers.SelectedItem
    // If you want to click same item more than once, set SelectedIndex to -1 after use it.
}