您的位置:首页 > 移动开发 > Objective-C

修复WPF Silverlight ListBox控件的一个Bug

2011-05-12 10:21 260 查看
  先来看这样演示程序。在修复前,选择重复的数字会导致选中状态混乱,出现多个数字莫名其妙被选中的状况。

 



  刨根问题,此问题最终定位到如下代码(WPF 项目,Silverlight项目类似):

 

01
/*
 

02
internal bool Select(object o,bool assumeInItemsCollection);
03
04
Declaring Type: System.Windows.Controls.Primitives.Selector+SelectionChanger
05
Assembly: PresentationFramework, Version=4.0.0.0
06
*/
07
internal
bool
Select(
object
o,
bool
assumeInItemsCollection)
08
{
09
if
(!Selector.ItemGetIsSelectable(o))
return
false
;
10
if
(!assumeInItemsCollection && !
this
._owner.Items.Contains(o))
11
{
12
if
(!
this
._toDeferSelect.Contains(o))
this
._toDeferSelect.Add(o);
13
return
false
;
14
}
15
if
(!
this
._toUnselect.Remove(o))
16
{
17
if
(
this
._owner._selectedItems.Contains(o))
return
false
;
18
if
(
this
._toSelect.Contains(o))
return
false
;
19
if
(!
this
._owner.CanSelectMultiple &&
this
._toSelect.Count >0) 
20
{
21
foreach
(
object
obj2
in
(IEnumerable)
this
._toSelect)
22
{
23
this
._owner.ItemSetIsSelected(obj2,
false
);
24
}
25
this
._toSelect.Clear();
26
}
27
this
._toSelect.Add(o);
28
}
29
return
true
;
30
}
  由于使用的是Items.Contains(o)判断,所以会导致值类型的重复数据判断出错。当然修复此问题的思想就是把值类型转换为引用类型。

  创建如下代码

01
public
class
WrapObject<T>
 

02
{
03
private
T _obj;
04
 
05
public
WrapObject(T o)
06
{
07
_obj = o;
08
}
09
 
10
public
static
implicit
operator
WrapObject<T>(T o)
11
{
12
return
new
WrapObject<T>(o);
13
}
14
 
15
public
static
explicit
operator
T(WrapObject<T>o) 
16
{
17
return
o._obj;
18
}
19
 
20
public
T UnWrap()
21
{
22
return
_obj;
23
}
24
 
25
public
override
string
ToString()
26
{
27
return
_obj ==
null
?
null
: _obj.ToString();
28
}
29
}
  绑定方法修改为

listBox2.ItemsSource =
new
WrapObject<
int
>[] {1, 2, 3, 4, 5, 6, 1, 4, 5, 2, 3, 6 };
 

  此问题到此解决

本文来自Aimeast的博客,原文地址:http://www.cnblogs.com/Aimeast/archive/2011/05/11/2043281.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息