Reputation: 289
I have a combobox that is binding to an ObservableCollection
of strings in an object. This binding works, but I also want to bind whatever the user selects from this combobox, in a different property which is a string, in the same Object. I cannot figure out whether I should use SelectedValue
or SelectedItem
, or if there is a problem beyond that. Thank you in advance.
Here is what I have so far, I have omitted any code irrelevant to the problem:
In XAML:
<Grid.Resources>
<my:JobItem x:Key="jobItemViewSource" />
</Grid.Resources>
<ComboBox x:Name="businessUnitBox" ItemsSource="{Binding Path=BusinessUnits}" IsSynchronizedWithCurrentItem="True">
<ComboBox.SelectedValue>
<Binding Path="BusinessUnit" Mode="TwoWay" UpdateSourceTrigger="Explicit" />
</ComboBox.SelectedValue>
</ComboBox>
Code behind:
public string BusinessUnit
{
get{ return businessUnit; }
set
{
if (String.IsNullOrEmpty(BusinessUnit) || !BusinessUnit.Equals(value))
{
businessUnit = value;
OnPropertyChanged("BusinessUnit");
}
}
}
public ObservableCollection<string> BusinessUnits
{
get { return businessUnits; }
set
{
if(!BusinessUnits.Equals(value))
{
businessUnits = value;
OnPropertyChanged("BusinessUnits");
}
businessUnits = value;
}
}
Upvotes: 5
Views: 39904
Reputation: 15247
You probably want to use SelectedItem
. That'll give the actual item that was bound to it. SelectedValue
is determined by the SelectedValuePath
property... which is just unnecessary in this case.
Also, you probably don't want to set the UpdateSourceTrigger
to be Explicit
. The default should be fine in that regard.
Upvotes: 9