Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding ComboBox item to string

Tags:

c#

combobox

wpf

I want to bind a ComboBox item to a string, but it does not work. My code is below.

Code in view:

<ComboBox          
 SelectedValuePath="content" 
 SelectedItem="{Binding ProductName}" 
            ......                       
 <ComboBoxItem>1111111111</ComboBoxItem>
 <ComboBoxItem>2222222222222</ComboBoxItem>
 <ComboBoxItem>333333333333</ComboBoxItem>
</ComboBox>

Code in view model:

private string _productName;
public string ProductName
{
    get { return _productName; }
    set
    {
        if (_productName != value)
        {
            _productName = value;
            RaisePropertyChangedEvent("ProductName");
        }
    } 
}
like image 780
YYang Avatar asked Sep 10 '15 08:09

YYang


2 Answers

I assume you want to get the text from the ComboboxItem and not the ComboBoxItem iteself.

So you are binding the wrong information. This should work.

<ComboBox          
SelectedValuePath="content" 
Text="{Binding ProductName}" 
            ......                       
<ComboBoxItem>1111111111</ComboBoxItem>
<ComboBoxItem>2222222222222</ComboBoxItem>
<ComboBoxItem>333333333333</ComboBoxItem>
</ComboBox>
like image 117
Joerg Avatar answered Sep 30 '22 03:09

Joerg


Selected Item is of type ComboBoxItem, it will not accept String. If you want to display product name in some other place try maybe something like this:

 <TextBox Text="{Binding ElementName=my_ComboBox, Path=SelectedItem}"/>
like image 28
DevNewb Avatar answered Sep 30 '22 03:09

DevNewb