繁体   English   中英

如何将控件绑定到列表 <string> ?

[英]How can I bind a control to a List<string>?

看起来像是一个非常基本的MVVM问题,但是谈到Catel时,我遇到了问题。

  • 我有一个属性-已注册,该属性是一个名为Lines的列表。
  • 我将其绑定到ListBox。
  • 我也有一个带有命令的Button,它向Lines添加了一个条目。
  • 线被映射到模型,并且当我检查模型的值时,我看到将值添加到线时它会正确更新。

因此,一切似乎都正常,除了修改Lines时我的视图没有更新

我试图通过在Lines的setter中以及在向Lines添加新值的命令中添加RaisePropertyChanged(“ Lines”)来解决此问题。

它为属性提供了以下内容:

[ViewModelToModel("MyModel", "Lines")]
public List<string> Lines
{
    get { return GetValue<List<string>>(LinesProperty); }
    set
    {
        SetValue(LinesProperty, value);
        RaisePropertyChanged("Lines");
    }
}

public static readonly PropertyData LinesProperty =
    RegisterProperty("Lines", typeof(List<string>), null, (s, e) => {});

这是命令的(是的,我在viewmodel的构造函数中有AddLine = new Command(OnAddLineExecute); ):

public Command AddLine { get; private set; }
private async void OnAddLineExecute()
{
    // this doesn't seem relevant, but since we're talking async and stuff, that may as well be the issue
    if (!lineCountChecked && Lines.Count >= 4)
    {
        if (await messageService.Show(MainDialogs.LineCountCheck, "Lines count", MessageButton.OKCancel, MessageImage.Warning) != MessageResult.OK)
            return;
        else
            lineCountChecked = true;                    
    }
    //

    Lines.Add("New Line");
    RaisePropertyChanged("Lines");
}

这很可能是一个非常愚蠢的错误,但我无法理解。 我错过了什么? 谢谢

您有2个选项可以使这项工作:

1)RaisePropertyChanged(()=> Lines)=>将更新整个集合2)使用ObservableCollection而不是List,以便UI可以实际响应更新

我推荐2。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM