我正在使用c#xaml开发Windows手机应用程序 我正在使用MVVM架构。
我有两个View Model
类
BaseViewModel:ViewModelBaseX
{
public override void OnNavigatedTo(NavigationMode mode, Uri uri, IDictionary<string, string> queryString)
{
// a condition is checking here & if the condition is true ,
i don't want to run the remaining codes in the AboutViewModel .
TOTO: have to stop the execution here & prevent execution
of remaining codes in the derived classes.
}
}
AboutViewModel:BaseViewModel
{
public override void OnNavigatedTo(NavigationMode mode, Uri uri, IDictionary<string, string> queryString)
{
base.OnNavigatedTo(mode, uri, queryString);
// here some code to be execute
}
}
我知道在baseviewmodel&amp;中设置属性标志的方法。在派生的视图模型中检查它 但它会使代码重复和必须在所有派生类中检查它。
还有其他方法可以从基类中找到它吗? 请帮忙!
答案 0 :(得分:2)
一种选择是将所有实际的OnNavigatedTo代码放在由基类OnNavigateTo调用的单独方法中。在基类上创建它作为受保护的方法(可能不做任何事情)并在派生类上重写它。然后基类只在它想要的时候调用它。
BaseViewModel:ViewModelBaseX
{
public override void OnNavigatedTo(NavigationMode mode, Uri uri, IDictionary<string, string> queryString)
{
// a condition is checking here & if the condition is true ,
i don't want to run the remaining codes in the AboutViewModel .
if (someCondition)
{
NavigateToFunctionality();
}
else
{
// do nothing
}
}
protected void NavigateToFunctionality()
{
}
}
AboutViewModel:BaseViewModel
{
public override void OnNavigatedTo(NavigationMode mode, Uri uri, IDictionary<string, string> queryString)
{
base.OnNavigatedTo(mode, uri, queryString);
}
protected override void NavigateToFunctionality()
{
// your code goes here
}
}
答案 1 :(得分:0)
最简单的方法是:
1 /在BaseViewModel中引入一个新的虚拟方法(称为&#34; HandleNavigatedTo&#34;)
2 /有BaseViewModel调用&#34; HandleNavigatedTo&#34;根据您的标准
3 /让BaseViewModel后代覆盖&#34; HandleNavigatedTo&#34;并用那种方法做他们的东西
4 /让BaseViewModel后代 NOT 覆盖&#34; OnNavigatedTo&#34;
public class BaseViewModel : ViewModelBaseX
{
protected virtual void HandleNavigatedTo(NavigationMode mode, Uri uri, IDictionary<string, string> queryString)
{
}
public override void OnNavigatedTo(NavigationMode mode, Uri uri, IDictionary<string, string> queryString)
{
if (condition)
{
HandleNavigatedTo(mode, uri, queryString);
}
}
}
public class AboutViewModel:BaseViewModel
{
public override void HandleNavigatedTo(NavigationMode mode, Uri uri, IDictionary<string, string> queryString)
{
// here some code to be execute
}
}