[英]data binding combobox in wpf
Code-Behind : 后台代码:
public class TestVariableClass
{
List<string> States;
public TestVariableClass()
{
States = new List<string> { "MP", "CG"};
}
}
XAML: 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>
I simply dont see my comboBox field getting populated when I run the application. 运行应用程序时,我根本看不到我的comboBox字段被填充。 Is my way of data binding correct ?
我的数据绑定方式正确吗? I was trying to connect this comboBox with my database column.
我试图将此comboBox与我的数据库列连接。 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; } }
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.
为此,您可以使用ObservableCollection而不是List。 You may not need that functionality though.
但是,您可能不需要该功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.