将 WPF 组合框绑定到新 Window 中的列表
Binding a WPF ComboBox to a List in new Window
我是 WPF 新手...
我正在尝试将列表绑定到新 Window 中的组合框。
列表如下class:
public class TestClass
{
public List<string> ComboBoxItems = new List<string>
{
"Item 1", "Item2"
};
}
从 MainWindow 创建了一个新的 TestWindow:
private void TestWindow_Click(object sender, RoutedEventArgs e)
{
var test = new TestClass();
var win = new TestWindow { DataContext = test };
win.Show();
}
在 XAML 中,我尝试将 ComboBoxItems 绑定到 ComboBox,例如:
<Window ...
Title="TestWindow" Height="200" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ComboBox Name="combo" ItemsSource="{Binding ComboBoxItems}"/>
</Grid>
</Window>
我想当我将这个新 window 的 DataContext 设置为我的 TestClass 的一个实例时,我就可以访问它的成员(包括列表 ComboBoxItems)并可以绑定它们。
但是组合框是空的:
你能告诉我我做错了什么吗?
顺便说一句:
XAML 编辑器中没有 IntelliSense?
有什么建议吗?
谢谢!
ComboBoxItems
需要是 属性 而不是字段才能成为 DataBinding
的来源
public List<string> ComboBoxItems { get; } = new List<string>
{
"Item 1", "Item2"
};
我是 WPF 新手...
我正在尝试将列表绑定到新 Window 中的组合框。
列表如下class:
public class TestClass
{
public List<string> ComboBoxItems = new List<string>
{
"Item 1", "Item2"
};
}
从 MainWindow 创建了一个新的 TestWindow:
private void TestWindow_Click(object sender, RoutedEventArgs e)
{
var test = new TestClass();
var win = new TestWindow { DataContext = test };
win.Show();
}
在 XAML 中,我尝试将 ComboBoxItems 绑定到 ComboBox,例如:
<Window ...
Title="TestWindow" Height="200" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ComboBox Name="combo" ItemsSource="{Binding ComboBoxItems}"/>
</Grid>
</Window>
我想当我将这个新 window 的 DataContext 设置为我的 TestClass 的一个实例时,我就可以访问它的成员(包括列表 ComboBoxItems)并可以绑定它们。
但是组合框是空的:
你能告诉我我做错了什么吗?
顺便说一句: XAML 编辑器中没有 IntelliSense?
有什么建议吗?
谢谢!
ComboBoxItems
需要是 属性 而不是字段才能成为 DataBinding
public List<string> ComboBoxItems { get; } = new List<string>
{
"Item 1", "Item2"
};