我是 WPF 的初学者,正在尝试将 ComboBox 的项目绑定(bind)到 ObservableCollection
我使用了这段代码:
XAML
<Window x:Class="comboBinding2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox x:Name="cmbTest" ItemsSource="{Binding Path=cmbContent}" Width="200" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>
</Window>
C#
public MainWindow()
{
cmbTest.ItemsSource = cmbContent;
cmbContent.Add("test 1");
cmbContent.Add("test 2");
InitializeComponent();
}
public ObservableCollection<string> cmbContent { get; set; }
在我尝试调试之前,这段代码没有出现任何错误,它抛出了错误:
目标调用错误
PresentationFramework.dll 中发生类型为“System.Reflection.TargetInvocationException”的未处理异常
谁能告诉我我做错了什么?
最佳答案
您当前的实现存在一些问题。正如其他人所说,您的列表当前为 NULL
,并且未设置 Window 的 DataContext
。
不过,我建议(特别是因为您刚开始使用 WPF)学习使用 MVVM
以更“正确”的方式进行绑定(bind)。
请参阅下面的简化示例:
首先,您要设置Window
的DataContext
。这将允许 XAML
“查看”您的 ViewModel
中的属性。
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
接下来,只需设置一个 ViewModel
类,它将包含所有 Window 的
绑定(bind)元素,例如:
public class ViewModel
{
public ObservableCollection<string> CmbContent { get; private set; }
public ViewModel()
{
CmbContent = new ObservableCollection<string>
{
"test 1",
"test 2"
};
}
}
最后,更新您的 XAML
,使绑定(bind)路径与集合匹配:
<Grid>
<ComboBox Width="200"
VerticalAlignment="Center"
HorizontalAlignment="Center"
x:Name="cmbTest"
ItemsSource="{Binding CmbContent}" />
</Grid>
关于c# - WPF ComboBox 绑定(bind) ItemsSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28373643/