简体   繁体   English

WPF ComboBox选定的项目参考一个对象

[英]WPF ComboBox Selected Item with reference to an object

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. 如果我仅使用String声明所选项目,但如果使用对象则不行,则可以正常工作。

<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? 有办法解决吗?

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 . 您不能创建新对象并将其分配给SelectedItem The Combobox simply compares object references not the content. 组合框仅比较对象引用而不是内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM