【问题标题】:WPF binding backcode objects to UI [closed]WPF 将 backcode 对象绑定到 UI [关闭]
【发布时间】:2013-09-10 18:35:50
【问题描述】:

谁能向我解释如何绑定集合,例如 String[] 对象到 WPF ListBox(在 xaml 中)以及它是如何工作的,因为我在阅读 MSDN 和其他网站上的教程后感到恶心。我仍然不知道该怎么做。

假设我在 MainWindow.xaml.cs 中有:

String[] bigBadWolf = {"1","2","3","4","5"};

我希望bigBadWolf 与 xaml 中的ListBox 绑定(我希望bigBadWolf 的每个成员垂直显示在ListBox 中(类似于播放列表)。

【问题讨论】:

    标签: c# wpf xaml data-binding listbox


    【解决方案1】:

    如果您打算使用MainWindow.xaml.cs,那么我建议您定义一个DependencyProperty 来代替:

    public static readonly DependencyProperty BigBadWolfProperty = DependencyProperty.
        Register("BigBadWolf", typeof(string[]), typeof(MainWindow), new
        UIPropertyMetadata(100.0));
    
    public string[] BigBadWolf
    {
        get { return (string[])GetValue(BigBadWolfProperty); }
        set { SetValue(BigBadWolfProperty, value); }
    }    
    

    然后,您必须设置您的DataContext... 最简单(但不是最好)的方法是在构造函数中执行此操作:

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }
    

    现在绑定到属性:

    <ListBox ItemsSource="{Binding BigBadWolf}" />
    

    请注意,在 WPF 中更常见的是使用 ObservableCollection&lt;T&gt; 集合。

    【讨论】:

    • 仍然没有得到它;/在 WPF 中不可能将列表之类的 Collection 对象绑定到 ListBox 的 ItemSource 属性。必须把这整个烂摊子搞定吗?
    • WPF 是一种与 WinForms 或 ASP.NET 非常不同的语言。如果你想用它来开发,那么你有很多东西要学。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 2011-04-24
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多