c# - WPF ComboBox 绑定(bind) ItemsSource

标签 c# wpf xaml data-binding combobox

我是 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)。

请参阅下面的简化示例:

首先,您要设置WindowDataContext。这将允许 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/

相关文章:

c# - 在 C# 中使用字符串格式的刹车线和粗体文本

WPF 在运行时设置键盘焦点,无需代码

wpf - Windows7是否使用WPF?

silverlight - 在 Silverlight 中即时调整 ChildWindow 高度会导致奇怪的行为

c# - 如何将枚举绑定(bind)到 WPF 中组合框的依赖属性?

c# - 为什么在这个例子中使用 float 比使用 double 慢 2 倍?

c# - 如果 secret 中的值发生变化, key 保管库值不会更新,因为它会为 secret 生成新版本

c# - 如何调用 UpdateSource() 以在 DataGrid 上进行显式绑定(bind)?

xaml - ViewModel 上的 BindableProperty 未更新

c# - 对于基于微服务的基础架构,应在 Azure B2C 中定义多少个应用程序?