2016-05-15 106 views
1

有沒有什麼方法可以在viewmodel內聲明依賴屬性?我想在viewmodel中聲明一個依賴屬性,並通過命令改變它的值。Prism中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不會在當前的背景下存在’。有沒有其他方法可以做到這一點?

+0

爲什麼它必須是一個依賴項屬性?視圖模型中的常規屬性應該足夠了。 – Haukinger

+0

我有兩個可視狀態,我想基於與數據觸發的行爲依賴屬性值的狀態之間切換。我想使用調用命令的行動,這將改變依賴屬性的值,因此,將狀態間切換 – siam

回答

0

A DependencyProperty用於DependencyObject,其示例是UserControl。棱鏡的ViewModelBase不是DependencyObject,主要是因爲這種類型是平臺特定的。爲了支持從視圖模型綁定,我們通常使用INotifyPropertyChanged

棱鏡實施在BindableBase基類,從中派生ViewModelBase以及該接口。定義你的屬性是這樣的:

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

如果您安裝了Prism Template Pack的Visual Studio擴展,可以使用propp代碼段。