Today I encountered an issue with the WPF standard CombBox where if the bound ItemsSource (collection) of a ComboBox has changed the binding on the SelectedItem of the ComboBox will fail to update to the already properly set view model property.

For example if the ItemsSource is bound to the following property of the view model which is common and presumably the best practice:

 public ObservableCollection<string> Items { get; private set; }

And the SelectedItem is bound to

 public string SelectedItem
{
get { return SelectedModel.SelectedItem; }
set
{
SelectedModel.SelectedItem = value;
OnPropertyChanged();
}
}

And the SelectedModel can be changed this way:

 public Model SelectedModel
{
get { return _selectedModel; }
set
{
if (_selectedModel != value)
{
_selectedModel = value; Items.Clear();
foreach (var item in _selectedModel.Items)
{
Items.Add(item);
} OnPropertyChanged("SelectedItem");
}
}
}

where each SelectedItem on SelectedModel has already been properly set up.

One might suppose it would work. However it doesn't.

The reason is kind of explained in this article,

http://stackoverflow.com/questions/5242275/combobox-itemssource-changed-selecteditem-is-ruined

As I've done a few experiments, I have feeling that the (initial) binding update is lost due to the fact that the framework modifies the SelectedItem property and holds certain assumptions as to the modification during the collection (Items) change and neglects property changed notification afterwards if things went against its assumption (no matter when it happens, and only not when the property actually changes from its value as of the end of the collection process).

Given the above speculation, I continued playing with the code and eventually come up with a workable solution like below (complete source code).

View model:

 using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using ComboBoxItemsSourceChangeTest.Annotations; namespace ComboBoxItemsSourceChangeTest
{
/// <summary>
/// The view model of the main UI
/// </summary>
/// <remarks>
/// http://stackoverflow.com/questions/5242275/combobox-itemssource-changed-selecteditem-is-ruined
/// </remarks>
public class MainViewModel : INotifyPropertyChanged
{
private Model _selectedModel; private bool _isComboTransitioning; public MainViewModel()
{
Items = new ObservableCollection<string>();
} public Model SelectedModel
{
get { return _selectedModel; }
set
{
if (_selectedModel != value)
{
_selectedModel = value; _isComboTransitioning = true;
Items.Clear();
foreach (var item in _selectedModel.Items)
{
Items.Add(item);
}
_isComboTransitioning = false; OnPropertyChanged("SelectedItem");
}
}
} public ObservableCollection<string> Items { get; private set; } public string SelectedItem
{
get
{
return _isComboTransitioning ? null: SelectedModel.SelectedItem;
}
set
{
if (SelectedModel.SelectedItem != value && !_isComboTransitioning)
{
SelectedModel.SelectedItem = value;
OnPropertyChanged();
}
}
} public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
} public void RaisePropertyChanged(string propertyName)
{
OnPropertyChanged(propertyName);
}
}
}

Model:

 namespace ComboBoxItemsSourceChangeTest
{
public class Model
{
public string[] Items { get; set; } public string SelectedItem { get; set; }
}
}

View:

 <Window x:Class="ComboBoxItemsSourceChangeTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<ComboBox Margin="10" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}"
Name="ComboBox1">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"></TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Margin="10" Name="Button1" Click="Button1_Click">Data Source 1</Button>
<Button Margin="10" Name="Button2" Click="Button2_OnClick">Data Source 2</Button>
<Button Margin="10" Name="Button3" Click="Button3_OnClick">Data Source 3</Button>
<Button Margin="10" Name="ButtonRandomSelect" Click="ButtonRandomSelect_OnClick">Random Select</Button>
</StackPanel>
</Grid>
</Window>

WPF standard ComboBox Items Source Change Issue的更多相关文章

  1. 关于WPF的ComboBox中Items太多而导致加载过慢的问题

    原文:关于WPF的ComboBox中Items太多而导致加载过慢的问题 [WFP疑难]关于WPF的ComboBox中Items太多而导致加载过慢的问题                          ...

  2. [WPF]ComboBox.Items为空时,点击不显示下拉列表

    ComboBox.Items为空时,点击后会显示空下拉列表: ComboBox点击显示下拉列表,大概原理为: ComboBox存在ToggleButton控件,默认ToggleButton.IsChe ...

  3. DevExpress WPF入门指南:跟随 Items Source 向导完成数据绑定

    Items Source Wizard Items Source Configuration Wizard允许在设计时执行数据绑定.跟随这个向导可以自动生成XAML数据绑定代码. 下面就来展示下如何使 ...

  4. WPF的ComboBox 数据模板自定义

    WPF的ComboBox 有些时候不能满足用户需求,需要对数据内容和样式进行自定义,下面就简要介绍一下用数据模板(DataTemplate)的方式对ComboBox 内容进行定制: 原型设计如下: 步 ...

  5. WPF 自定义ComboBox样式,自定义多选控件

    原文:WPF 自定义ComboBox样式,自定义多选控件 一.ComboBox基本样式 ComboBox有两种状态,可编辑和不可编辑状态.通过设置IsEditable属性可以切换控件状态. 先看基本样 ...

  6. WPF之ComboBox的VisualTreeHelper

    原文:WPF之ComboBox的VisualTreeHelper 用WPF的ComboBox控件的时候,需要用到TextChanged属性,但是这个属性属于TextBox控件,不用担心,ComboBo ...

  7. 【WPF】ComboBox:根据绑定选取、设置固定集合中的值

    问题场景 我有一个对象,里面有一个属性叫Limit,int类型.虽然int可取的范围很大,我想要在用户界面上限制Limit可取的值,暂且限制为5.10.15.20. 所以ComboBox绑定不是绑定常 ...

  8. WPF中ComboBox用法

    The ComboBox control is in many ways like the ListBox control, but takes up a lot less space, becaus ...

  9. WPF 关于ComboBox在前台绑定XML数据的一些方法,使用XML数据提供器 XmlDataProvider

    关于使用 数据提供器:XmlDataProvider 的一些问题,以及在WPF中是如何使用的一些介绍,还有踩到的一些坑,希望其他和我碰到一样问题的,可以更快的解决. 首先,要求是 在WPF 的前台代码 ...

随机推荐

  1. 注意kvm在安装虚机的时候不能把存放虚机的文件放在/root 下面

    如果放在/root下面会报错: WARNING KVM acceleration not available, using 'qemu' Starting install... Creating st ...

  2. SQL错误级别 状态 怎么定义

    关于SQL Server的错误严重性级别的说明,强烈认真看一下下面的两个链接 脱机帮助 ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.zh-CHS/sqlerrm9/html/ ...

  3. Delphi基本数据类型---枚举、子界、集合、数组

    参考:http://blog.csdn.net/qustdong/article/details/9230743 参考:http://www.cnblogs.com/xumenger/p/440222 ...

  4. 【php全局变量和静态变量、静态方法的使用方法】

    php全局变量使用关键字global声明,静态变量使用static声明,静态变量的使用可以使用 类名::变量名 示例代码: <?php //全局变量global 的用法和静态变量的使用 glob ...

  5. 关于phpcms v9投票模块选项排序listorder设定问题

    关于phpcms v9投票模块选项排序listorder设定问题修改,主要修改了三个文件三处地方. 主要修改三个文件: .phpcms\modules\vote\templates\vote_edit ...

  6. [Outlook] 重新取得outlook中被禁止访问的文件

    摘要:接收到老大的邮件,邮件中带有jar包,导致我无法接收到这个文件,outlook2010中提示:outlook禁止访问不安全……,相信很多人都遇到过这个问题,以前也遇到过,总没去想着解决这个问题, ...

  7. php获取当前毫秒时间戳

    最近在做一个智能家居项目的后台,需要实时上传用户对智能设备的配置信息到服务器,以便实现同步,因此对于时间的精确度要求比较高,最开始直接是用php的time()函数来获取时间戳,获取的时间精确到秒级别, ...

  8. HYSBZ 1588 营业额统计

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1588 题意:详见题面,中文 思路:平衡树的模板题. 可用Treap,Splay,Scape ...

  9. DOM--4 响应用户操作和事件(1)

    简介 事件:事件并不是以"on"开头的.例如,onclick引用的是一个对象的属性,click才是事件. 事件侦听器:当指定的事件发生时会执行的函数或方法. 事件注册:为DOM元素 ...

  10. js-其他