在WPF中未加载ComboBox项

时间:2016-08-03 08:30:33

标签: c# wpf visual-studio combobox wpf-controls

我的组合框项目未显示。它在2015年的visual studio上运行良好。但是当我在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;
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个

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>

它的作品!