Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComboBox SelectedValue or SelectedItem Binding WPF C#

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;
    }
}
like image 561
Erika Avatar asked Jun 21 '12 14:06

Erika


1 Answers

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.

like image 95
Tim Avatar answered Oct 19 '22 17:10

Tim