2011-07-28 21 views
0

我上次在Windows Phone 7應用程序中提交了有關在MVVM中使用屬性的問題。 我可以很好的建議。請看我以前的問題。如何劃分MVVM中的屬性類和方法類

Can not bind textblock property from another class to UI class using MVVM

通過我的編碼,MVVM性正在增加。所以我想分割屬性類和方法。 但我無法分割它。請讓我知道如何在MVVM中劃分屬性類和方法類。

我的代碼在這裏。

Authentication.cs

public class Authentication : ViewModelBase 
{ 
    private string _ErrorStatus; 
    public string ErrorStatus 
    { 
     get 
     { 
      return _ErrorStatus; 
     } 
     set 
     { 
      _ErrorStatus = value; 
      NotifyPropertyChanged("ErrorStatus"); 
     } 
    } 

    void Authenticate() 
    { 
     ErrorStatus = "Access Denied"; 
    } 
} 

我想這樣來劃分。但是「ErrorStatus」沒有改變。

Properties.cs

public class Properties : ViewModelBase 
{ 
    private string _ErrorStatus; 
    public string ErrorStatus 
    { 
     get 
     { 
      return _ErrorStatus; 
     } 
     set 
     { 
      _ErrorStatus = value; 
      NotifyPropertyChanged("ErrorStatus"); 
     } 
    } 
} 

Authentication.cs

public class Authentication 
{ 
    Properties properties = new Properties(); 

    void Authenticate() 
    { 
     //not work 
     properties.ErrorStatus = "Access Denied"; 
    } 
} 
+0

我可以推薦你開始使用http://code.google.com/p/notifypropertyweaver/,以避免你現在有大量的樣板文件。 –

回答

1

下使Authentication有機會獲得的Properties性能,並顯示它如何工作。

public class Properties : ViewModelBase 
{ 
    private string _ErrorStatus; 
    public string ErrorStatus 
    { 
     get 
     { 
      return _ErrorStatus; 
     } 
     set 
     { 
      _ErrorStatus = value; 
      RaisePropertyChanged("ErrorStatus"); 
     } 
    } 
} 

public class Authentication : Properties 
{ 
    public void Authenticate() 
    { 
     ErrorStatus = "Access Denied"; 
    } 
} 

public partial class MainPage : PhoneApplicationPage 
{ 
    public MainPage() 
    { 
     InitializeComponent(); 

     var test = new Authentication(); 

     test.Authenticate(); 

     MessageBox.Show(test.ErrorStatus); // Displays "Access Denied" 
    } 
} 
+0

感謝您的評論。但它沒有工作... –

+0

@okame我已經更新了答案,以顯示這是如何工作的。如果這不是你想要達到的能力,請你更新這個問題來澄清 –

+0

這很酷!我可以通過您的解決方案解決我的問題。非常感謝!! –

0

我假設你有同樣的舊

private Authentication authentication; 
public MainPage() 
{ 
    InitializeComponent(); 
    this.authentication = new Authentication(); 
    this.DataContext = authentication; 
} 
void btnAuthenticate_Click(object src, EventArgs e) 
{ 
    authentication.Authenticate(); 
} 

public class Authentication 
{ 
    private string properties = new Properties(); 
    public string Properties 
    { 
     get 
     { 
      return properties; 
     } 
     set 
     { 
      properties = value; 
      NotifyPropertyChanged("Properties"); 
     } 
    } 
    void Authenticate() 
    { 
     Properties.ErrorStatus = "Access Denied"; 
    } 
} 

正常的XAML應該然後是

<TextBlock Text="{Binding Path=Properties.ErrorStatus}" /> 

但有時,你改變了屬性的實例。 所以,如果它不工作,你可以試試這個XAML

<Border DataContext="{Binding Properties}"> 
    <TextBlock Text="{Binding Path=ErrorStatus}" /> 
</Border> 
+0

謝謝!我會試試看! –