如何正确地用代码设置ListBox的当前选中项
1个回答
展开全部
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
namespace SelectListBoxItem
{
/// <summary>
///
/// </summary>
public class ListBoxService
{
AutoSelect Property
private static void OnAutoSelectPropertyChanged(DependencyObject element, DependencyPropertyChangedEventArgs e)
{
if (!(element is UIElement))
return;
if ((bool)e.NewValue)
(element as UIElement).GotFocus += new RoutedEventHandler(OnElementGotFocus);
else
(element as UIElement).GotFocus -= new RoutedEventHandler(OnElementGotFocus);
}
private static void OnElementGotFocus(object sender, RoutedEventArgs e)
{
Debug.Assert(e.OriginalSource is DependencyObject);
ListBoxItem item = (e.OriginalSource as DependencyObject).FindAncestor<ListBoxItem>();
if (item != null)
item.IsSelected = true;
else
Debug.WriteLine(string.Format("Cannot find ListBoxItem from {0}", sender));
}
}
}
using System.Windows;
using System.Windows.Controls;
namespace SelectListBoxItem
{
/// <summary>
///
/// </summary>
public class ListBoxService
{
AutoSelect Property
private static void OnAutoSelectPropertyChanged(DependencyObject element, DependencyPropertyChangedEventArgs e)
{
if (!(element is UIElement))
return;
if ((bool)e.NewValue)
(element as UIElement).GotFocus += new RoutedEventHandler(OnElementGotFocus);
else
(element as UIElement).GotFocus -= new RoutedEventHandler(OnElementGotFocus);
}
private static void OnElementGotFocus(object sender, RoutedEventArgs e)
{
Debug.Assert(e.OriginalSource is DependencyObject);
ListBoxItem item = (e.OriginalSource as DependencyObject).FindAncestor<ListBoxItem>();
if (item != null)
item.IsSelected = true;
else
Debug.WriteLine(string.Format("Cannot find ListBoxItem from {0}", sender));
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询