您的位置:首页 > 编程语言

[WPF]如何正确地用代码设置ListBox的当前选中项

2009-01-12 23:56 501 查看
有人可能会说这有什么好写的。不就是一行代码就能搞定的吗?而且为什么需要用代码设置SelectedItem呢?用户所点的Item不就自动是SelectedItem吗?在这里将要讨论我们的,就是ListBox自己没有能自己把SelectedItem设置正确的情况。本来想当作一个WPF Bug清单的一篇文章的,但是又感觉也许就是有这样变态的需求呢。

我们用一个非常简单的代码的XAML就可以重现这个问题。

<Window x:Class="SelectListBoxItem.DemoWindow"

2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

4 xmlns:s="clr-namespace:System;assembly=mscorlib"

5 Title="ListBox Selection Problem"

6 SizeToContent="Height"

7 Width="300">

8 <ListBox>

9 <ListBox.ItemTemplate>

10 <DataTemplate>

11 <TextBox Text="{Binding .}" Width="100"/>

12 </DataTemplate>

13 </ListBox.ItemTemplate>

14 <s:String>a</s:String>

15 <s:String>b</s:String>

16 <s:String>c</s:String>

17 </ListBox>

18</Window>

运行的效果如下。

using System.Diagnostics;

2using System.Windows;

3using System.Windows.Controls;

4

5namespace SelectListBoxItem

6

其中FindAncestor是自己定义的一个方法,因为单纯地使用VisualTreeHelper是不足以在所有情况下找到Parent的。代码可参见源代码

写好了怎么用呢?我们说了,要以对现有代码最小的变动实现这个功能。可能有人已经想到了,用Style,那个Window的代码根本不用动。只要在App.xaml里加上一个Resource就OK了。代码如下,简单吧。

<Application x:Class="SelectListBoxItem.App"

2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

4 xmlns:l="clr-namespace:SelectListBoxItem"

5 StartupUri="DemoWindow.xaml">

6 <Application.Resources>

7 <Style TargetType="{x:Type ListBox}">

8 <Setter Property="l:ListBoxService.AutoSelect" Value="True"/>

9 </Style>

10 </Application.Resources>

11</Application>

12

到此,ListBox的行为算是正常些了。正常的运行截图就不发了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: