繁体   English   中英

WPF ComboBox绑定ItemsSource

[英]WPF ComboBox binding ItemsSource

我是WPF的初学者,并试图将ComboBox的Items绑定到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 ,并且未设置Window的DataContext

虽然,我建议(特别是因为你刚刚开始使用WPF)学习使用MVVM以更“正确”的方式进行绑定。

请参阅下面的简化示例:

首先,您要设置WindowDataContext 这将允许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>
   public MainWindow()
    {

        InitializeComponent();
        cmbContent=new ObservableCollection<string>();
        cmbContent.Add("test 1");
        cmbContent.Add("test 2");
        cmbTest.ItemsSource = cmbContent;

    }
    public ObservableCollection<string> cmbContent { get; set; }

上面的代码不使用任何绑定,这意味着使用它不需要绑定Combobox's ItemSource ,如果你不想使用绑定你需要

第一步 :使用以下命令从CodeBehind(ViewModel)设置DataContext:

this.DataContext=this;

或者来自Xaml:

DataContext="{Binding RelativeSource={RelativeSource Self}}">

第二 :在ItemSource中使用Binding就像你使用ItemsSource="{Binding Path=cmbContent}" ,如果你想在属性发生任何变化时通知UI,你也可以考虑使用INotifyPropertyChanged接口。

cmbContent为null,因为您从未将其设置为任何内容。 我猜这个错误实际上是一个NullReferenceException ,但是它显示为TargetInvocationException因为它位于视图的构造函数中。

此外,您将两次设置ComboBoxItemsSource (一次在绑定中,一次在构造函数中)。 你不需要这样做。 选一个。 您的绑定将无法DataContext编写方式工作(因为未设置DataContext ),因此您应该在代码中执行此操作,或者设置DataContext (如Nadia所建议的那样)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM