加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – WPF ComboBox绑定ItemsSource

发布时间:2020-12-16 00:25:02 所属栏目:百科 来源:网络整理
导读:我是 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/winf
我是 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以更“正确”的方式进行绑定.

请参阅下面的简化示例:

首先,您要设置Window的DataContext.这将允许XAML“查看”ViewModel中的属性.

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

接下来,只需设置一个ViewModel类,它将包含所有Window的绑定元素,例如:

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读