[英]ListBox SelectedItem is always null
當我單擊ListBox中的項目時,它始終返回null。 當然我的ListBox已經裝滿了:-)
我的XAML代碼:
<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>
我的C#代碼:
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";
}
當我單擊它時,我的sender
項目始終為空。 問題是什么? 謝謝你的幫助!
您應該處理ListViewItem
,而不是ListBox
。 只需在ListView.ItemContainerStyle
為ListViewItem
創建處理程序:
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
}
}
您應該改用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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.