在WPF应用程序中绑定集合的各个元素

时间:2017-05-19 10:34:43

标签: c# wpf xaml

这是WPF应用程序,我正在尝试绑定TextBlock中的单个集合项属性。我在StackOverflow上搜索,其他许多人也提出了类似的问题,他们的解决方案也在运行。我尝试以相同的方式访问值,但不知何故,它在我的情况下没有显示索引值,所以发布类似的问题。请帮我识别我在这里做错了什么。

查看模型

public class SequeanceViewModel
{
    public ObservableCollection<Sequence> SequenceList = new ObservableCollection<ViewModel.Sequence>();
    public SequeanceViewModel()
    {
        for (int i = 1; i <= 6; i++)
        {
            SequenceList.Add(new ViewModel.Sequence() { Index = i, Name = "Name goes here" });
        }
    }
}

public class Sequence : INotifyPropertyChanged
{
    private int index { get; set; }
    private bool current { get; set; }
    private string name;
    public int Index
    {
        get
        {
            return index;
        }
        set
        {
            index = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Index"));
        }
    }
    public bool Current
    {
        get
        {
            return current;
        }
        set
        {
            current = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Current"));
        }
    }
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
            OnPropertyChanged(new PropertyChangedEventArgs("Name"));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, e);
        }
    }
}

窗口代码

SequeanceViewModel sequeanceViewModel;
public Validation()
{
    InitializeComponent();

    sequeanceViewModel = new SequeanceViewModel();
    this.DataContext = sequeanceViewModel;

}

以xaml绑定

<TextBlock Text="{Binding SequenceList[0].Index, Mode=OneWay}"></TextBlock>

2 个答案:

答案 0 :(得分:2)

由于您只能绑定到公共属性,因此必须将SequenceList定义为属性而不是公共字段:

public ObservableCollection<Sequence> SequenceList { get; } = new ObservableCollection<ViewModel.Sequence>();

答案 1 :(得分:0)

您必须将SequenceList公开为属性而不是公共变量。否则你无法绑定它。