【问题标题】:Dependency property inside viewmodel in PrismPrism中视图模型内的依赖属性
【发布时间】:2016-05-15 17:29:53
【问题描述】:

有没有办法在视图模型中声明依赖属性?我想在 viewmodel 中声明一个依赖属性并通过命令更改它的值。

public class MyViewModel : Prism.Windows.Mvvm.ViewModelBase
    {
        public bool IsPaneVisible
        {
            get { return (bool)GetValue(IsPaneVisibleProperty); }
            set { SetValue(IsPaneVisibleProperty, value); }
        }

        public static readonly DependencyProperty IsPaneVisibleProperty =
            DependencyProperty.Register("IsPaneVisible", typeof(bool), typeof(MyViewModel), new PropertyMetadata(0));

        public ICommand VisibilityChangeCommand { get; set; }

        public MyViewModel()
        {
            VisibilityChangeCommand = new DelegateCommand(OnVisibilityChange);
        }

        private void OnVisibilityChange()
        {
            IsPaneVisible = !IsPaneVisible;
        }
    }

问题是,我在 IsPaneVisible 的 getter/setter 中遇到一些编译错误:“GetValue 在当前上下文中不存在”。有没有其他方法可以做到这一点?

【问题讨论】:

  • 为什么它必须是依赖属性?视图模型中的常规属性应该足够了。
  • 我有两个视觉状态,我想根据依赖属性值和数据触发行为在这些状态之间切换。我想使用调用命令操作来改变依赖属性的值,从而在状态之间切换

标签: mvvm prism dependency-properties


【解决方案1】:

DependencyProperty 用于DependencyObject,例如UserControl。 Prism 的 ViewModelBase 没有DependencyObject,主要是因为这个类型是平台特定的。为了支持从视图模型绑定,我们通常使用INotifyPropertyChanged

Prism 在 BindableBase 基类中实现此接口,ViewModelBase 也从该基类派生。您可以这样定义您的属性:

private string _imagePath;
public string ImagePath
{
    get { return _imagePath; }
    set { SetProperty(ref _imagePath, value); }
}

如果您安装了Prism Template Pack Visual Studio 扩展,则可以使用propp 代码 sn-p。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多