wpf中的数据绑定组合框 [英] data binding combobox in wpf

查看:123
本文介绍了wpf中的数据绑定组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码背后:

public class TestVariableClass
{
    List<string> States;

    public TestVariableClass()
    {
    States = new List<string> { "MP", "CG"};           
    }
}

XAML:

<Window x:Class="TestApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestApplication"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <local:TestVariableClass x:Key="StatesInIt"/>
</Window.Resources>
<Grid>
    <StackPanel Orientation="Horizontal" VerticalAlignment="Top" DataContext="{StaticResource StatesInIt}">
        <Label>States</Label>
        <ComboBox Width="140" Margin="5" x:Name="comboBoxStates" ItemsSource="{Binding States}"></ComboBox>
    </StackPanel>
</Grid>

我根本看不到我的comboBox我运行应用程序时填充字段。我的数据绑定方式是否正确?
我试图将此comboBox与我的数据库列连接。但是,在尝试了几件事情之后,我意识到这个错误在绑定本身。

I simply dont see my comboBox field getting populated when I run the application. Is my way of data binding correct ? I was trying to connect this comboBox with my database column. But after trying out few things I realised the error was in the binding itself.

推荐答案

你在模型类中绑定了什么需要成为该类的公共财产:

What you are binding to in your model class needs to be a public property of the class:

private List<string> _states;

public List<string> States { get { return _states; } }

作为注释,您将无法修改国家集合并拥有在视图中自动更新。为此,您可以使用ObservableCollection而不是List。您可能不需要该功能。

As a note, you won't be able to modify the collection of States and have it update automatically in the view. For that, you could use an ObservableCollection instead of a List. You may not need that functionality though.

这篇关于wpf中的数据绑定组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆