WPF用委托实现子窗体之间互相切换
有时候一个在导航下需要多个子窗体之间实现相互切换,此功能可以使用委托来实现;
主窗体MainViewModel定义委托:
public class MainViewModel: ViewModelBase
{
public static Action<int> SetAction { get; set; }
public MainViewModel()
{
SetAction = MyAction;
}
private FrameworkElement _mainContent;
public FrameworkElement MainContent
{
get { return _mainContent; }
set { _mainContent = value; RaisePropertyChanged(nameof(MainContent)); }
}
public BaseCommand NavgationCommand => new BaseCommand((obj) => {
Window[] childArray = Application.Current.Windows.Cast<Window>().ToArray();
Type type = Type.GetType("WpfApp10.Views." + obj.ToString());
ConstructorInfo cti = type.GetConstructor(System.Type.EmptyTypes);
this.MainContent = (FrameworkElement)cti.Invoke(null);
});
private void MyAction(int index)
{
ShowWindow(index);
}
private void ShowWindow(int index)
{
string hwn = "";
switch(index)
{
case 1:
hwn = "UserControl1";
break;
case 2:
hwn = "UserControl2";
break;
case 3:
hwn = "UserControl3";
break;
case 4:
hwn = "UserControl4";
break;
default:
break;
}
Window[] childArray = Application.Current.Windows.Cast<Window>().ToArray();
Type type = Type.GetType("WpfApp10.Views." + hwn.ToString());
ConstructorInfo cti = type.GetConstructor(System.Type.EmptyTypes);
this.MainContent = (FrameworkElement)cti.Invoke(null);
}
}
子窗体互相切换则调用委托:
class UserControl1ViewModel : ViewModelBase
{
public UserControl1ViewModel()
{
}
public BaseCommand FunctionCommand => new BaseCommand((obj) => {
MainViewModel.SetAction(2);
});
}
效果:
点击上方的导航栏可切换下方的子窗体,点击下方子窗体中的按钮也可以切换子窗体;