繁体   English   中英

wpf中的数据绑定组合框

[英]data binding combobox in 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与我的数据库列连接。 但是在尝试了几件事之后,我意识到错误在于绑定本身。

您要在模型类中绑定的内容必须是该类的公共属性:

private List<string> _states;

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

注意,您将无法修改状态集合,也无法在视图中自动更新它。 为此,您可以使用ObservableCollection而不是List。 但是,您可能不需要该功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM