简体   繁体   中英

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

Seems like a very basic MVVM question, but when it comes to Catel, I have issues doing it.

  • I have a property - registered as it should - which is a List, named Lines.
  • I bind it to a ListBox.
  • I also have a Button with a command adding a entry to Lines.
  • Lines is mapped to a model, and when I check the values of the model, I see it gets updated correctly when adding a value to Lines.

So everything seems to work, except that my view isn't updating when Lines is modified .

I tried to solve this by adding a RaisePropertyChanged("Lines") in Lines' setter, and in the command that adds a new value to Lines.

It gives something like this for the property:

[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) => {});

and this for the command (yes, I have AddLine = new Command(OnAddLineExecute); in the viewmodel's constructor):

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");
}

It's more than likely a very stupid mistake, but I can't get it. What did I miss? Thanks

You have 2 options to make this work:

1) RaisePropertyChanged(() => Lines) => will update the whole collection 2) Use ObservableCollection instead of List so the UI can actually respond to updates

I recommend 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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