Skip to main content

Microsoft Silverlight

Unanswered Question ComboBox problem with SelectedItem BindingRSS Feed

(0)

tearaway_Tea
tearaway...

Member

Member

2 points

2 Posts

ComboBox problem with SelectedItem Binding

Hi guys, I've got a problem and found a solution. But I would like to share my experience and to hear all possible walk-arounds.

So I have a combobox with setted via binding ItemsSource and SelectedItem (both are binded on datacontext view model properties):

<UserControl x:Class="TestComboBox.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
		xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
		xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="640"
		d:DesignHeight="480">
	<StackPanel x:Name="LayoutRoot" Orientation="Horizontal" VerticalAlignment="Center">
		
		<ComboBox x:Name="TestItemsComboBox" 
				  ItemsSource="{Binding TestItems}" 
				  SelectedItem="{Binding SelectedItem, Mode=OneWay}">
			<ComboBox.ItemTemplate>
				<DataTemplate>
					<TextBlock Text="{Binding Name}" />
				</DataTemplate>
			</ComboBox.ItemTemplate>
		</ComboBox>
		
		<Button Content="Repopulate" 
				Click="OnRepopulateButtonClick" />
		
		<Button Content="Select Item Programatically" 
				Click="OnSelectProgramaticallyButtonClick" />
		
		<Button Content="Select the first item via binding"
				Click="OnSelectViaBindingButtonClick" />
	</StackPanel>
</UserControl>
 

The code-behind class is:

using System;
using System.Collections.Generic;
using System.Windows;

namespace TestComboBox
{
	public partial class MainPage
	{
		public MainPage()
		{
			InitializeComponent();
			DataContext = new MainPageViewModel();
		}

		private void OnRepopulateButtonClick(object sender, RoutedEventArgs e)
		{
			var items = new List();
			var count = new Random(Environment.TickCount).Next(3, 10);

			for (var i = 0; i < count; i++)
			{
				var item = new TestItem {Name = "Name" + i, Description = i.ToString()};
				items.Add(item);
			}

			((MainPageViewModel)DataContext).TestItems = items;
		}

		private void OnSelectProgramaticallyButtonClick(object sender, RoutedEventArgs e)
		{
			TestItemsComboBox.SelectedItem =
				((MainPageViewModel) DataContext).TestItems[0];
		}

		private void OnSelectViaBindingButtonClick(object sender, RoutedEventArgs e)
		{
			((MainPageViewModel) DataContext).SelectedItem = 
				((MainPageViewModel) DataContext).TestItems[0];
		}
	}
}

When I click Repopulate button I re-create the TestItems collection for view model which is a binding source for ItemsSource property in combobox and my view model has a code for selecting the first item from the collection

using System.Collections.Generic;
using System.ComponentModel;

namespace TestComboBox
{
	public class TestItem
	{
		public string Name { get; set;}
		public string Description { get; set; }
	}

	public class MainPageViewModel : INotifyPropertyChanged
	{
		private List _testItems;
		private TestItem _selectedItem;

		public List TestItems
		{
			get { return _testItems; }
			set
			{
				_testItems = value;

				if (PropertyChanged != null)
				{
					PropertyChanged(this, new PropertyChangedEventArgs("TestItems"));
				}

				SelectedItem = value[0];
			}
		}

		public TestItem SelectedItem
		{
			get { return _selectedItem; }
			set
			{
				_selectedItem = value;

				if (PropertyChanged != null)
				{
					PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem"));
				}
			}
		}

		public event PropertyChangedEventHandler PropertyChanged;
	}
}

So, for the first time it works as expected: the combobox is being populated and the first item is being selected. But if I click Repopulate button one-more time, the combobox will get new item list but it will not select the first item. And that is a BUG. I have created two other buttons to check that is going on and I've realise out a weird behavior. If I update SelectedItem for viewmodel (by clicking "Select item via binding" button) then combobox doesn't react on that action (it seems it ignores binding proccess), but if I set SelectedItem for the combobox manually(by clickin "Select item programatically" button) it is being selected.

So my solution it to use TwoWay binding here:

		<ComboBox x:Name="TestItemsComboBox" 
				  ItemsSource="{Binding TestItems}" 
				  SelectedItem="{Binding SelectedItem, Mode=TwoWay}">

After that code update the combobox selects the first item each time I update TestItems. But actually I don't really need TwoWay binding here because the combobox is sending null value to the view model each time while it is being repopulated by new TestItems.

Do you have any ideas about this issue? Is it a bug or I just don't understand the Silverlight Binding lifecycle.

Thanks.

ArtiBot
ArtiBot

Member

Member

2 points

1 Posts

Re: ComboBox problem with SelectedItem Binding

Hi,

 I have experienced something similar. It turns out that the object that you set to the SelectedItem, should be comming from the object collection that you set to your combobox ItemsSource. When you use a different collection ( even with the same objects ) it does not seem to find a match. I guess internally it uses a reference to these objects. And the reference is different every time you create a new instance of the objects.

This is also imprtant to note when you use data from a static resource, in XAML and code behind, you should always use the same collection of objects. At least that is my experience.

 

 

  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities