Silverlight ComboBox的SelectedValue不在ItemSource中的绑定失败问题。

正在实践简单的MVVM。使用ComboBox进行数据下拉选择绑定,然后就遇到问题了。

左侧ListBox中有三项数据,ComboBox中只有2项。左边选中绑定到右边。

123

1.当选中共有的数据项,wang和xu时一切正常。

2.当选择xie时,因为ComboBox里没有这个选项,所以ComboBox里应该没有选中项,这是可以理解的。

3.但是当再次选择共有的数据项时,ComboBox里的选择就绑不上了。

无尽的google之后,或许是google技术欠佳,没有找到好的解决方法。只能自己动手了。

先自定义一个控件继承ComboBox。

public class NoValueComboBox : ComboBox

找一找有没有绑定时出错的事件,发现没有,只能注册选择项变化的事件。

代码
public NoValueComboBox()
{
this.SelectionChanged += new SelectionChangedEventHandler(NullableComboBox_SelectionChanged);

}

void NullableComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

}

观察e,发现当没有选择项时e.AddedItems.Count = 0,或许可以在这个时候控制下。

数次尝试之后怀疑是绑定出了问题。觉得或许在这时候重新绑定下就能继续用了。

先是怀疑ItemSource。

代码
if (e.AddedItems == null || e.AddedItems.Count == 0)
{
var be
= this.GetBindingExpression(NoValueComboBox.ItemsSourceProperty);
var b
= be.ParentBinding;
this.SetBinding(NoValueComboBox.ItemsSourceProperty, b);
}

发现无用。又怀疑SelectedValue。

代码
void NullableComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems == null || e.AddedItems.Count == 0)
{
var be
= this.GetBindingExpression(NoValueComboBox.ItemsSourceProperty);
var b
= be.ParentBinding;
this.SetBinding(NoValueComboBox.ItemsSourceProperty, b);
be
= this.GetBindingExpression(NoValueComboBox.SelectedValueProperty);
b
= be.ParentBinding;
this.SetBinding(NoValueComboBox.SelectedValueProperty, b);
}
}

这个时候神奇的报错了。在获取SelectedValueProperty的绑定值时获取的是Null。原来在这时候SelectedValue已经没有绑定了,那么难怪接下去的数据都绑不上了。是否可以在控件加载的时候,就是 在SelectedValue还有绑定值的时候获取绑定参数,然后存在全局变量里,再在适当的时候再次给SelectedValue赋值。多次尝试之后获得代码如下:

代码
public class NoValueComboBox : ComboBox
{
Binding _binding;

public NoValueComboBox()
{
this.SelectionChanged += new SelectionChangedEventHandler(NullableComboBox_SelectionChanged);
}

public override void OnApplyTemplate()
{
base.OnApplyTemplate();

var be
= this.GetBindingExpression(NoValueComboBox.SelectedValueProperty);
_binding
= be.ParentBinding;
}

void NullableComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems == null || e.AddedItems.Count == 0)
{
this.SetBinding(NoValueComboBox.SelectedValueProperty, _binding);
}
}
}

看看效果。

123

下面那个ComboBox就是自定义的,看起来还行。

或许有更好的办法,请大家指点。

code:demo

     <ComboBox Height="20" Width="60"

                  DisplayMemberPath="Name"

                  SelectedValuePath="Age"

                  SelectedValue="{Binding Age,Mode=TwoWay}"

                  ItemsSource="{Binding Persons}"/>

posted @ 2010-12-23 19:29  超时空饭盒  阅读(2571)  评论(2编辑  收藏  举报