WPF 绑定和属性定义

WPF binding and definition of properties

我正在使用 ViewModel 的 LinkCollection-属性 进行绑定,LinkCollection 填充在 ViewModel 的构造函数中:

    public SurveySelectionViewModel()
    {
        foreach (var year in Surveys().Select(x => x.year.ToString()).Distinct())
        {
            this.Years.Add(new Link { DisplayName = year, Source = new Uri("http://www.whosebug.com") });
        }
    }

当我的 ListCollection "Years" 定义如下时,年份显示在视图中:

private LinkCollection years = new LinkCollection();
public LinkCollection Years
{
    get { return this.years; }
    set
    {
        if (this.years != value)
        {
            this.years = value;
        }
    }
}

为什么不显示年份我把上面的内容缩减为:

public LinkCollection Years = new LinkCollection();

LinkCollection 仍在填充多年..但它们没有显示。

因为 public LinkCollection Years = new LinkCollection();Years 定义为字段,而不是 属性,并且您不能绑定到 WPF 中的字段。

你可以这样做:

public LinkCollection Years { get; private set; }

然后在构造函数中设置 Years

Years = new LinkCollection();