问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/48008220/wpf-combobox-selected-item-with-reference-to-an-object