Ahsan
Ahsan

Reputation: 658

"SelectedValue" of comboBox in WPF has correct value but with additional text of namespace

"SelectedValue" of comboBox in WPF has correct value but with additional text of namespace. I am following MVVM, "SelectedValue" is binded to "SelectedImage" property.

If I select first comboBoxItem, its value is "System.Windows.Controls.ComboBox:Firmware Image 1".

How to get only selected value?

            <ComboBox Grid.Row="1"
              Grid.Column="1"
              Width="150"
              Height="30"
              ToolTip="Store Identification"
              Margin="0,2,10,0"
              HorizontalAlignment="Right"
              VerticalAlignment="Top"
              Background="#FF1649A0"
              BorderBrush="White"
              Foreground="White"

              SelectedValue="{Binding SelectedImage}">
            <ComboBox.Items>
                <ComboBoxItem Content="Firmware Image 1 " />
                <ComboBoxItem Content="Firmware Image 2" />
            </ComboBox.Items>
        </ComboBox>

Upvotes: 1

Views: 139

Answers (2)

WPFGermany
WPFGermany

Reputation: 1649

If you bind the items to a List or ObservableCollection you're done.

<ComboBox ItemsSource="{Binding Images}" SelectedValue="{Binding SelectedImage}" />

viewmodel:

public ObservableCollection<string> Images { get; } = new ObservableCollection<string> { "Firmware Image 1", "Firmware Image 2" }; 
public string SelectedImage { get; set; } //Maybe implemented with Notify for Two-Way Binding

**EDIT (second possibility): **

If you like to keep your items defined in xaml you could easyly use this:

<ComboBox SelectedItem="{Binding SelectedImage}">
    <ComboBox.Items>
        <ComboBoxItem Content="DisplayText1" />
        <ComboBoxItem Content="DisplayText2" />
    </ComboBox.Items>
</ComboBox>

viewmodel:

//to get the text use: (SelectedImage as ComboBoxItem).Content
public object SelectedImage { get; set; }

Bind to an object in codebehind and you can perform the Content property.

Upvotes: 1

Rom
Rom

Reputation: 1193

Use strings, there you go:

 <ComboBox Grid.Row="1"
          Width="150"
          Height="30"
          ToolTip="Store Identification"
          Margin="0,2,10,0"
          HorizontalAlignment="Right"
          VerticalAlignment="Top"
          Background="#FF1649A0"
          BorderBrush="White"
          Foreground="White"
           SelectedValue="{Binding SelectedImage}" >
        <ComboBox.Items>
            <sys:String>Firmware Image 1</sys:String>
            <sys:String>Firmware Image 2</sys:String>
        </ComboBox.Items>
    </ComboBox>

Add the namespace:

  xmlns:sys="clr-namespace:System;assembly=mscorlib"

Upvotes: 1

Related Questions