ComboBox 项目未在 WPF 中加载

ComboBox Item is not loaded in WPF

我的组合框项目没有显示。它在 visual studio 2015 上运行良好。但是当我在 visual studio 2013 年尝试此操作时,它什么也没显示。我在 ComboBox_Loaded 函数中设置了调试点,从中我看到编译器跳过了最后 3 行。我该如何解决 Visual Studio 2013 年的问题。在此先感谢您。

<Window x:Class="GraphicalUserInterface.ShowDataByObjectsWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ShowDataByObjectsWindow" Height="300" Width="300">
<Grid Background="#FFE5E5E5">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0" Margin="10">
        <TextBlock FontWeight="Bold" Text="Object Options"/>
        <ComboBox  x:Name="dbObjects" Loaded="ComboBox_Loaded" SelectionChanged="ComboBox_SelectionChanged"/>
    </StackPanel>
</Grid>

public partial class ShowDataByObjectsWindow : Window
{
    public List<string> dataTableName = new List<string>();
    public static string comboItem;

    public ShowDataByObjectsWindow()
    {
        InitializeComponent();          
    }

    private void ComboBox_Loaded(object sender, RoutedEventArgs e)
    {
        dataTableName.Add("adasd");
        dataTableName.Add("adaasdsd");


        var comboBox = sender as ComboBox;
        comboBox.ItemsSource = dataTableName;
        comboBox.SelectedIndex = 0;
    }

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var comboBox = sender as ComboBox;

        string value = comboBox.SelectedItem as string;
        this.Title = "Selected: " + value;
    }
}

试试这个

public ObservableCollection<String> Items { get; set; }

//public 
public MainWindow()
{
    InitializeComponent();

    Items = new ObservableCollection<string>();
    Items.Add("test");

    DataContext = this;
}

并改变你的看法

<Window x:Class="WpfApplication1.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 HorizontalAlignment="Left" ItemsSource="{Binding Path=Items}" Margin="155,56,0,0" VerticalAlignment="Top" Width="120"/>

    </Grid>
</Window>

成功了!