簡體   English   中英

在WPF應用程序中綁定集合的各個元素

[英]Bind individual elements of collection in WPF application

這是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>

由於只能綁定到公共屬性,因此必須將SequenceList定義為屬性,而不是公共字段:

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

您必須將SequenceList公開為屬性而不是公共變量。 否則,您將無法綁定到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM