【问题标题】:Bind a class member to a listbox将类成员绑定到列表框
【发布时间】:2015-02-02 05:31:52
【问题描述】:

我是 wpf 的初学者。在我的一个项目中,我有一个 frmField 类,如下所示:

public class frmFields
{
    public bool succelssfulEnd = true;
    public string fileName;
    public List<string> errList = new List<string>();
}  

还有一个列表

<ListBox Name="LSTErrors" Grid.Row="11" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource ="{Binding}"  SelectionChanged="LSTErrors_SelectionChanged" />

我需要将 errList 绑定到上面的 listBox,这样 List 中的任何更改都会反映在 ListBox 上。

有人指导我吗?

【问题讨论】:

  • 如果您可以阅读 VB.Net,那么我以前的 answer here 会有所帮助。不要忘记设置 Window 的 DataContext,然后您的 ListBox 将自动继承该 DataContext(除非您首先在可视树中的某个位置重置它)。并使用属性或依赖属性,而不是字段。

标签: wpf list xaml binding listbox


【解决方案1】:

您需要一个 ObservableCollection 来在 UI 每次更改时刷新它。

public class frmFields
{
    public bool succelssfulEnd = true;
    public string fileName;

    private ObservableCollection<String> _errList = new ObservableCollection<String>();
    public ObservableCollection<String> ErrList {
        get {return _errList;}
        set {
            _errList = value;
            //your property changed if you need one
        }
    }
}

请注意,您只能绑定到 Property 或 DependencyProperty,而不是像您尝试的那样简单的公共变量。

在您的构造函数中,您需要添加:

this.DataContext = this;

或在您的 XAML 中:

DataContext="{Binding RelativeSource={RelativeSource self}}"

在你的根元素中。然后像这样绑定 ItemsSource:

<ListBox ItemsSource="{Binding ErrList, Mode=OneWay}">
     ...
</ListBox>

【讨论】:

    猜你喜欢
    • 2013-10-26
    • 1970-01-01
    • 2014-08-25
    • 2019-10-01
    • 2018-06-20
    • 2019-12-17
    • 2011-08-28
    • 2012-10-21
    • 1970-01-01
    相关资源
    最近更新 更多