简体   繁体   中英

Update a property when another property changes in Prism

I have something like that in my view model

        public ObservableCollection<string> UnitSystems { get; set; }
        private string selectedUnitSystem;
        public string SelectedUnitSystem
        {
            get { return selectedUnitSystem; }
            set { SetProperty(ref selectedUnitSystem, value); }
        }

        private string _property1Unit;
        public string Property1Unit
        {
            get { return _property1Unit; }
            set { SetProperty(ref _property1Unit, value); }
        }

They are bound to a combobox and label in my view. I want to update the value Property1Unit and content of the label of course, when I select something else in my combobox. Is it possible?

Yes it is possible. You can pass in any action you want to perform after the value you are setting. The sample below shows a case where you have a value that concatenates two strings for a FirstName and a LastName. This will only execute when the property is changed, so if the value is Dan and the new value is Dan it will not execute since it will not raise PropertyChanged in the first place.

public class ViewAViewModel : BindableBase
{
    private string _firstName;
    public string FirstName
    {
        get => _firstName;
        set => SetProperty(ref _firstName, value, () => RaisePropertyChanged(nameof(FullName));
    }
    private string _lastName;
    public string LastName
    {
        get => _lastName;
        set => SetProperty(ref _lastName, value, () => RaisePropertyChanged(nameof(FullName));
    }

    public string FullName => $"{FirstName} {LastName}";
}

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