Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage combobox and complex objects

Tags:

c#

combobox

wpf

I am trying to figure out how to handle Combobox with complex objects.

I have the following 2 classes:

BackupVersion.cs

public class BackupVersion
{
public string Name { get; set; }
public BackupVersion() { }

    public BackupVersion(string name)
    {
        Name = name;
    }
}

SubsystemVersions.cs

public class SubsystemVersions : ObservableCollection<BackupVersion>
{
    public SubsystemVersions()
    {
        Add(new BackupVersion("amit"));
        Add(new BackupVersion("aaa"));
        Add(new BackupVersion("ofir"));
    }

}

I also have to following XAML window:

<Grid>
    <StackPanel>
        <StackPanel.Resources>
            <local:SubsystemVersions x:Key="Backups"/>
        </StackPanel.Resources>
        <ComboBox Name="c1"
                  ItemsSource="{StaticResource Backups}"
                  Text="mmm"
                  DisplayMemberPath="Name"
                  SelectedValuePath="Name"
                  IsEditable="true"
                  IsReadOnly="true"/>
        <TextBlock Text="{Binding ElementName=comboBox1, Path=SelectedItem}"/>
    </StackPanel>
</Grid>

This way, in the code behind, I can get the selected string in the combobox using:

this.c1.SelectedValue.ToString()

My question is, how can I get back the original object i.e. the BackupVersion object?

Please also comment on the coding style, if I am doing something which is not common (for example, is that the best way to define and bind the collection?)

like image 753
amitfr Avatar asked Dec 07 '25 09:12

amitfr


1 Answers

To get back the original object :

this.c1.SelectedItem;
like image 128
Joffrey Kern Avatar answered Dec 09 '25 21:12

Joffrey Kern



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!