Mister 832
Mister 832

Reputation: 1221

Bind ComboBox to Displaymember to Object

I've got a ComboBox which has a SortedList<int, double> as ItemsSource that contains the Number of Items and the Price (which is fairly complicated to deduce). The user can select the number of Items and a textbox on the page shows the price for these items. Hence, I set the DisplayMember to NumberOfItems and the ValueMember to Price. This works fine.

However, now I want to store the Number of Items in an Orders class; not the price! I couldn't find any examples of how to this, only binding to SelectedValue, which is not what I want to do. (I'am well aware, that this use of the combobox is quite the "other way around":) )

I tried binding to SelectedItem, but that doesn't seem to work:

BindingOperations.SetBinding(NumberOfItemsCombo, ComboBox.SelectedItemProperty, new Binding("NumberOfItems") { Source = Order});

Is it possible to bind the NumberOfItems to the something like the "SelectedDisplayValue"?

Thanks!

Edit: Example: The Sortedlist contains the following values:

Index   NumberOfItems   Price
[0]:    {[1,            41]}
[1]:    {[2,            82]}
[2]:    {[3,            123]}
[3]:    {[4,            164]}
[4]:    {[5,            205]}
[5]:    {[6,            246]}
[6]:    {[7,            287]}
[7]:    {[8,            328]}
[8]:    {[9,            369]}
[9]:    {[10,           410]}

The ComboBox should Dispay the Column NumberOfItems (ie 1 - 10). If the user selects a value, say 7, a Textbox displays the Price, in the example 287. The order class has a property NumberOfItems which I want to bind to ComboBox. So once the Property is set to a certain number, say 6, the combobox should display 6 and the textbox 246.

Edit II:

Thanks to Liero it works fine now in xaml. Now I only need to do the binding of the Textbox in Code. However, this is not working:

BindingOperations.SetBinding(PriceTextBox, TextBox.TextProperty, new Binding() { Source=ComboBox, Path = new PropertyPath("SelectedItem.Price") });

Figured it out: The direction was missing. Now it works!

BindingOperations.SetBinding(PriceTextBox, TextBox.TextProperty, new Binding() { Source=ComboBox, Path = new PropertyPath("SelectedItem.Price"), Mode = BindingMode.OneWay });

Upvotes: 0

Views: 466

Answers (1)

Liero
Liero

Reputation: 27338

Do you want to replace SortedList where key is NumberOfItems and value is Price with something more intuitive?

public class Order 
{
   public int NumberOfItems {get; set;}
   public double Price {get; set;}
}

comboBox1.ItemsSource = new List<Order>
{
    new Order { NumberOfItems = 1, Price = 20 }
    new Order { NumberOfItems = 2, Price = 40 }
}
<ComboBox x:Name="comboBox1" DisplayMemberPath="NumberOfItems"/>
<TextBlock Text="{Binding SelectedItem.Price, ElementName=comboBox1}" />

Upvotes: 1

Related Questions