Reputation: 5815
I have page like this ...
<Page x:Class="WPFTestRig.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1">
<Grid>
<StackPanel>
<ComboBox Name="myBox" ItemsSource="{Binding Path=MyCollection}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True"
SelectedItem="{Binding Path=SelectedEntryValue}" SelectedValuePath="Name" SelectedValue="{Binding Path=SelectedEntryValue}"/>
</StackPanel>
</Grid>
</Page>
with code behind as
public partial class Page1 : Page
{
private List<Entry> _myCollection;
private string _selectedEntryValue;
public Page1()
{
InitializeComponent();
_myCollection = new List<Entry>();
_myCollection.Add(new Entry { Name = "Test1", Id = 1 });
_myCollection.Add(new Entry { Name = "Test2", Id = 2 });
_myCollection.Add(new Entry { Name = "Test3", Id = 3 });
_selectedEntryValue = "Test3";
myBox.DataContext = this;
}
public List<Entry> MyCollection
{
get {
return _myCollection;
}
}
public string SelectedEntryValue
{
get {
return _selectedEntryValue;
}
set {
_selectedEntryValue = value ;
}
}
}
public class Entry
{
public string Name { get; set; }
public int Id { get; set; }
}
when i put a break point on set property of SelectedEntryValue property, i see it gets called twice, once with the string of the type name like (MyTestApp.Entry) and then the actual selected value
can someone point out what i should be doing for it to work right ?
many thanks
Upvotes: 1
Views: 235
Reputation: 62909
Your problem is that you accidentally bound both SelectedItem
and SelectedValue
.
You wrote (reformatted for readability):
<ComboBox Name="myBox" ... SelectedValuePath="Name" ...
SelectedItem="{Binding Path=SelectedEntryValue}"
SelectedValue="{Binding Path=SelectedEntryValue}" />
Remove the SelectedItem
binding and you will get the behavior you expect.
Upvotes: 2
Reputation: 64068
You're seeing that behavior because you bind it to both SelectedItem
and SelectedValue
, thus it executes twice. The first time it is bound it appears the displayed property is not being used yet.
Upvotes: 1