绑定ComboBox ItemsSource在WPF中不起作用

Rob*_*ter 6 c# wpf xaml binding combobox

这有点奇怪,因为我发现那里的每个示例都说我正在以正确的方式进行操作,但仍无法使ComboBox绑定在WPF中工作。

我刚刚创建了一个空的WPF应用程序。

public List<string> myCollection { get; set; }

    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();
        myCollection = new List<string> {"test1", "test2", "test3", "test4"};
    }
Run Code Online (Sandbox Code Playgroud)

这是我的xaml:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <ComboBox ItemsSource="{Binding Path=myCollection}" Height="23" HorizontalAlignment="Left" Margin="66,56,0,0" Name="comboBox1" VerticalAlignment="Top" Width="319" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

我尝试了绑定myCollection,绑定路径= myCollection,无论是否设置DataContext,我都尝试过。似乎没有任何作用。

我的想法已经用尽了,我发现那里的每个示例都说这是正确的方法,应该可以正常工作,因此,感谢您提供的任何帮助。

Saj*_*ran 5

设置数据上下文 InitializeComponent

 InitializeComponent();          
 myCollection = new List<string> { "test1", "test2", "test3", "test4" };
 DataContext = this;
Run Code Online (Sandbox Code Playgroud)


Dim*_*nis 5

在构造函数的末尾

comboBox1.ItemsSource = myCollection;
Run Code Online (Sandbox Code Playgroud)

  • @RobertPorter那么你应该按照上面的建议设置DataContext! (2认同)