将类成员绑定到列表框

时间:2014-12-04 10:58:52

标签: wpf list xaml binding listbox

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

有没有人可以指导我?

1 个答案:

答案 0 :(得分:0)

每次更改时都需要一个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>
相关问题