简体   繁体   中英

Why can I not populate an array in my back-end C# that I declare in my ViewModel?

I have this code in my VM and it works okay:

public ParamViewModel[] CardChoice { get; set; } = new[] 
    {
        new ParamViewModel { Id = 0, Name = CC.All.ShortText(), IsSelected = false, 
            BackgroundColor="#FFFFFF", TextColor="#999999", BorderColor="#999999" },
        new ParamViewModel { Id = 1, Name = CC.Catg.ShortText(), IsSelected = false, 
            BackgroundColor="#FFFFFF", TextColor="#999999" , BorderColor="#999999" },
    };

I changed it to this as I think I should not populate data in the VM but it seems not to work as expected:

VM

public ParamViewModel[] CardChoice { get; set; }

C# back-end

vm.CardChoice = new[] 
    {
        new ParamViewModel { Id = 0,  Name = CC.All.ShortText(),   IsSelected = false, 
            BackgroundColor="#FFFFFF", TextColor="#999999" , BorderColor="#999999" },
        new ParamViewModel { Id = 1,  Name = CC.Catg.ShortText(),  IsSelected = false, 
            BackgroundColor="#FFFFFF", TextColor="#999999" , BorderColor="#999999" }
    };

But now nothing appears in the controls that use this data as back-end. Is there a problem with the way I am populating the data in the back-end?

Change your VM code like below.

When you assing the property on a later stage than the UI is rendered then you have to use the INotifyPropertyChanged to tell the Renderer to rerender

public class YourVM : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private ParamViewModel[] cardChoice;

    public ParamViewModel[] CardChoice
    {
        get { return cardChoice; }
        set 
        { 
            cardChoice = value;
            OnPropertyChanged("CardChoice")
        }
    }
}

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