Prism中视图模型内的依赖属性

3

有没有办法在ViewModel内声明依赖属性?我想在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在当前上下文中不存在”。有没有其他的方法来解决这个问题?


为什么必须使用依赖属性?在视图模型中,普通属性应该足够了。 - Haukinger
我有两个可视状态,想基于依赖属性值和数据触发行为在这些状态之间切换。我想使用Invoke命令操作来改变依赖属性的值,从而在状态之间进行切换。 - Yeasin Abedin
1个回答

3
一个 DependencyProperty 在一个 DependencyObject 上使用,例如 UserControl。Prism的ViewModelBase不是DependencyObject,主要是因为这种类型是针对特定平台的。为了支持从ViewModel进行绑定,我们通常使用 INotifyPropertyChanged

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接