I have a ComboBox with 2 items whose contents are databound to 2 dependency properties (Foo and Bar).
I have a button which increases Foo and Bar.
When I press this button, I see in the output window that Foo and Bar have indeed changed. Setting a breakpoint on the binding (SL 5 only) also proves this point.
But the value displayed on the ComboBox is not updated!
It is only updated when I click on the ComboBox or change the selected item via [TAB] and [DOWN].
I even tried to call UpdateLayout() on my ComboBox after the values update but to no avail.
Here’s my code for you to test.
Code behind:
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
namespace ComboBoxBindingTest
{
public partial class MainPage : UserControl
{
public int Foo
{
get { return (int)GetValue(FooProperty); }
set { SetValue(FooProperty, value); }
}
public static readonly DependencyProperty FooProperty =
DependencyProperty.Register("Foo", typeof(int), typeof(MainPage), new PropertyMetadata(0));
public int Bar
{
get { return (int)GetValue(BarProperty); }
set { SetValue(BarProperty, value); }
}
public static readonly DependencyProperty BarProperty =
DependencyProperty.Register("Bar", typeof(int), typeof(MainPage), new PropertyMetadata(0));
public MainPage()
{
Foo = 0;
Bar = 0;
InitializeComponent();
DataContext = this;
}
private void Step()
{
Foo++;
Bar++;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Step();
Debug.WriteLine("Foo: {0}", Foo);
Debug.WriteLine("Bar: {0}", Bar);
}
}
}
XAML:
<UserControl x:Class="ComboBoxBindingTest.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:DesignHeight="138"
d:DesignWidth="188">
<StackPanel Background="White">
<ComboBox Width="120"
Height="23"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<ComboBoxItem Content="{Binding Foo}"
IsSelected="True" />
<ComboBoxItem Content="{Binding Bar}" />
</ComboBox>
<Button Content="Step"
Width="75"
Height="23"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Click="Button_Click" />
</StackPanel>
</UserControl>
What am I doing wrong, here?
The Silverlight Combobox is only updating it’s text when the selection is changes as you already experienced. You can create your custom Combobox which can change it’s text on different events. Or (as a not so nice workaround) you can re-select the currently selected item:
EDIT: An alternative solution
If you are not adding the combobox items manually but bind the combobox to a viewmodel collection you can achieve the same result (although the code will be quite different from what you have right now)
ViewModel for the items:
Code behind:
XAML