首页 > 解决方案 > 当 Prism 中的另一个属性发生变化时更新一个属性

问题描述

我的视图模型中有类似的东西

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

在我看来,它们绑定到组合框和标签。当我在组合框中选择其他内容时,我当然想更新标签的值 Property1Unit 和内容。可能吗?

标签: c#mvvmprism

解决方案


对的,这是可能的。您可以在您设置的值之后传入您想要执行的任何操作。下面的示例显示了一个情况,其中您有一个连接 FirstName 和 LastName 的两个字符串的值。这只会在属性更改时执行,因此如果值是Dan并且新值是Dan,它将不会执行,因为它不会首先引发 PropertyChanged。

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

推荐阅读