2012-03-19 187 views
0

獲取屬性我有這樣的視圖模型:從視圖模型

public class BaseViewModelTech : INotifyPropertyChanged 
{ 


    static string _TechnicianID; 
    public string TechnicianID 
    { 
     get {     
      return _TechnicianID; 
     } 
     set { 

      _TechnicianID = TechnicianID; 
      OnPropertyChanged("TechnicianID"); 
     } 

    } 

    static string _DeviceID; 
    public string DeviceID 
    { 
     get 
     { 
      return _DeviceID; 
     } 
     set 
     { 
      _DeviceID = DeviceID; 
      OnPropertyChanged("DeviceID"); 
     } 

    } 



    // In ViewModelBase.cs 
    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     this.VerifyPropertyName(propertyName); 

     PropertyChangedEventHandler handler = this.PropertyChanged; 
     if (handler != null) 
     { 
      var e = new PropertyChangedEventArgs(propertyName); 
      handler(this, e); 
     } 
    } 

    [Conditional("DEBUG")] 
    [DebuggerStepThrough] 
    public void VerifyPropertyName(string propertyName) 
    { 
     // Verify that the property name matches a real, 
     // public, instance property on this object. 
     if (TypeDescriptor.GetProperties(this)[propertyName] == null) 
     { 
      string msg = "Invalid property name: " + propertyName; 
      Debug.Fail(msg); 
     } 
    } 
} 

我把它作爲參數傳遞給我的xaml.cs

public partial class BaseView : Window{ 
    BaseViewModelTech viewModel; 
     public BaseView (BaseViewModelTech vm) 
     { 
      InitializeComponent(); 
      viewModel = vm; 
     }} 

做什麼我寫來訪問它使用throught XAML捆綁??我沒有理解多個例子。

+0

'OnPropertyChanged'應該叫**後:

public partial class BaseView : Window{ BaseViewModelTech viewModel; public BaseView (BaseViewModelTech vm) { InitializeComponent(); viewModel = vm; this.DataContext=viewModel; }} 
在你我xaml.xaml例如用於標籤

然後**改變價值。 – 2012-03-19 12:25:00

+0

@ H.B。 yes = D fixed – Nahum 2012-03-19 12:26:06

+0

您應該閱讀[數據綁定概述](http://msdn.microsoft.com/zh-cn/library/ms752347.aspx)。 – 2012-03-19 12:30:15

回答

2

更改代碼視圖稍微落後:

public partial class BaseView : Window 
{ 
    BaseViewModelTech viewModel; 

    public BaseView (BaseViewModelTech vm) 
    { 
     InitializeComponent(); 
     viewModel = vm; 
     this.DataContext = vm; // <----------- add this 
    } 
} 

,然後在XAML,你可以有這樣的事情:

<TextBlock Text="{Binding TechnicianID}" /> 

還要注意的是,在你的制定者,你想要做的通知屬性值改變,而不是之前:

set 
    { 
     _DeviceID = DeviceID; 
     OnPropertyChanged("DeviceID"); // <------ this goes after the member variable change 
    } 
+0

哦,是的!謝謝!我並沒有讓WPF工作幾個月,突然間又有了一個截止日期爲昨天= D的項目 – Nahum 2012-03-19 12:33:06

1

在你的情況下,由於你的vm實例是你View的成員,你不能直接將你的ViewModel引用到xaml中。所以,你應該先設置你的觀點的DataContext的代碼隱藏:

<Label Content="{Binding TechnicianID }"/>