Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 绑定枚举时,WPF组合框为空_C#_Wpf_Combobox - Fatal编程技术网

C# 绑定枚举时,WPF组合框为空

C# 绑定枚举时,WPF组合框为空,c#,wpf,combobox,C#,Wpf,Combobox,我试图将枚举的值绑定到组合框,但组合框仍然为空,没有可选择的选项 这是组合框xaml定义: <ComboBox Grid.Row="2" Grid.Column="1" ItemsSource="{Binding Path=SkillItemSource}" SelectedItem="{Binding Path=neededSkill, Mode=TwoWay}" SelectedIndex="0" Margin="5" MinWidth="100"></ComboBox&g

我试图将枚举的值绑定到组合框,但组合框仍然为空,没有可选择的选项

这是组合框xaml定义:

<ComboBox Grid.Row="2" Grid.Column="1" ItemsSource="{Binding Path=SkillItemSource}" SelectedItem="{Binding Path=neededSkill, Mode=TwoWay}" SelectedIndex="0" Margin="5" MinWidth="100"></ComboBox>
组合框中显示的值缺少什么

组合框中显示的值缺少什么

您需要将组合框的
DataContext
或父元素设置为定义了
SkillItemSource
属性的类的实例。如果属性是在代码隐藏中定义的,则可以将DataContext设置为视图本身:
this.DataContext=this

此外,你不能混合类型。如果
ItemsSource
绑定到
IEnumerable
,则
SelectedItem
属性应绑定到
字符串
属性

还请注意,
needeskill
必须定义为公共属性,您才能绑定到它

试试这个:

public Skill neededSkill { get; set; } = Skill.FirstSkill;

public IEnumerable<Skill> SkillItemSource { get; } = Enum.GetValues(typeof(Skill)).Cast<Skill>();
public Skill neededSkill{get;set;}=Skill.FirstSkill;
public IEnumerable SkillItemSource{get;}=Enum.GetValues(typeof(Skill)).Cast();

可能就是您要查找的内容。当Combobox的ItemsSource为type string[]时,您不能将SelectedItem设置为type Skill。即使DataContext是在同一窗口的xaml.cs中定义的,我也需要设置它吗?是的。如果属性是在代码隐藏中定义的,则可以将DataContext设置为视图本身:
this.DataContext=this
public Skill neededSkill { get; set; } = Skill.FirstSkill;

public IEnumerable<Skill> SkillItemSource { get; } = Enum.GetValues(typeof(Skill)).Cast<Skill>();