我是WPF的初学者,尝试将ComboBox的项目绑定到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; }
在尝试调试之前,我不会在此代码上遇到任何错误,它会引发错误:
TargetInvocationError
PresentationFramework.dll中发生了类型为'System.Reflection.TargetInvocationException'的未处理异常
有人可以告诉我我在做什么错吗?
您当前的实现存在一些问题。如其他人所述,您的列表当前为NULL
,并且DataContext
未设置窗口的。
不过,我建议(尤其是因为您刚开始使用WPF)建议使用来学习以更“正确”的方式进行绑定MVVM
。
请参见下面的简化示例:
首先,你要设置DataContext
你的Window
。这将允许XAML
“查看”中的属性ViewModel
。
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
接下来,只需设置一个ViewModel
包含所有Window's
绑定元素的类,例如:
public class ViewModel
{
public ObservableCollection<string> CmbContent { get; private set; }
public ViewModel()
{
CmbContent = new ObservableCollection<string>
{
"test 1",
"test 2"
};
}
}
最后,更新XAML
,使绑定路径与集合匹配:
<Grid>
<ComboBox Width="200"
VerticalAlignment="Center"
HorizontalAlignment="Center"
x:Name="cmbTest"
ItemsSource="{Binding CmbContent}" />
</Grid>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句