0

I'm trying to define a selected item in a combobox. It working fine if I'm just using a String to declare the selected item but not if using an object.

<ComboBox HorizontalAlignment="Left"
  VerticalAlignment="Top" Width="81" materialDesign:HintAssist.Hint="Woche" Margin="10" 
  ItemsSource="{Binding weekSelection}" 
  DisplayMemberPath="name" 
  SelectedItem="{Binding nodeWeek, Mode=TwoWay}"  
SelectedValue="name" />

-

private week _nodeWeek;
public week nodeWeek
{
    get
    {
       return _nodeWeek;
    }
    set
    {
        _nodeWeek = value;
        RaisePropertyChanged("nodeWeek");
    }
}

-

 public class week
 {
    public int val { get; set; }

    public String name { get; set; }
 }

- setting the selected item

this.nodeWeek = new week() { val = times.GetIso8601WeekOfYear(DateTime.Now), name = "KW " + times.GetIso8601WeekOfYear(DateTime.Now).ToString() };

Is there a way to fix that?

M.Y.Mnu
  • 718
  • 8
  • 22
ManuKILLED
  • 71
  • 1
  • 11
  • Could you try to bind with datasource property ? https://stackoverflow.com/questions/561166/binding-wpf-combobox-to-a-custom-list – BLU Dec 28 '17 at 13:19

1 Answers1

2

The selected item must be always one of the list of your items source. You cannot create new objects and assign them to the SelectedItem. The Combobox simply compares object references not the content.

gomi42
  • 2,449
  • 1
  • 14
  • 9
  • Thanks! How can I get the reference based on the ObservableCollection? I need to select an item of the Collection by "val" oder "name" – ManuKILLED Dec 28 '17 at 13:35
  • That is the easy part. Just `Find` the entry: nodeWeek = weekSelection.Find(x => x.name == TheNameYouWantToFind); – gomi42 Dec 28 '17 at 14:00
  • Just for example. If I'm trying to set the reference like this: nodeWeek = weekSelection[1]; it's still not working, there must be something else wrong I guess – ManuKILLED Dec 28 '17 at 14:05
  • Hm, in my test scenario it does work. Is the `DataContext` set correctly? – gomi42 Dec 28 '17 at 14:43