如何在MVVM中划分属性类和方法类

时间:2011-07-28 14:42:37

标签: windows-phone-7

上次,我在Windows Phone 7应用中提交了一个关于在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";
    }
}

2 个答案:

答案 0 :(得分: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"
    }
}

答案 1 :(得分: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}" />

但有时,您更改了Properties实例。 所以,如果它不起作用,你可以尝试这个xaml

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