
[英]How to pass parameters to usercontrol's viewmodel through window's xaml?
[英]WPF - Prism - how to pass parameters to Drawer's ViewModel
这是一个示例。我拥有的 xaml 代码,我正在使用MaterialDesignInXamlToolkit中的DrawerHost
控件
<UserControl
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DataContext="{d:DesignInstance viewModels:UserControlViewModel}"
mc:Ignorable="d"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes">
<materialDesign:DrawerHost IsRightDrawerOpen="{Binding IsDrawerOpen}" OpenMode="Default">
<materialDesign:DrawerHost.RightDrawerContent>
<views:RightDrawerView />
</materialDesign:DrawerHost.RightDrawerContent>
<!-- Main Content -->
</materialDesign:DrawerHost>
</UserControl>
RightDrawerViewModel
将通过 Prism 的ViewModelLocationProvider
设置为RightDrawerView
的 DataContext。
我的问题:将IsDrawerOpen
设置为 true 时, UserControlViewModel
如何将参数传递给RightDrawerViewModel
? 因为RightDrawerViewModel
不是通过 Prism 的方法( regionManager?.RequestNavigate
, dialogService?.ShowDialog
)调用的。
如果要传递参数,您可以RequestNavigate
而不是设置IsDrawerOpen
(它需要一个区域和一个自定义RegionAdapter
的DrawerHost
),或者您创建一个既要打开抽屉的视图 model 和抽屉的视图 model 都知道的服务并在设置IsDrawerOpen
之前将所有数据放在那里。
第三种选择是在您想要打开抽屉并将其分配给父视图 model 上的属性并将其绑定到抽屉内容的数据上下文时创建一个新的DrawerViewModel
。 此外,删除IsDrawerOpen
并将其替换为观察父级视图模型属性的样式或转换器。
只有当我被迫首先查看 go 时,我才会将 go 作为第一个选项,否则总是更喜欢第三个。 第二个是丑陋的,只是为了完整而呈现。
我的解决方案..
RightDrawerViewModel
中定义NavigationParameters
属性public class RightDrawerViewModel {
public NavigationParameters NavigationParameters { set; get; }
}
在我的例子中,我已经预定义了实现INavigationAware
的BaseViewModel
,所以我向它添加了 NavigationParameters 属性(这样我可以保存通过RequestNavigate
传递的参数,即使对于从BaseViewModel
继承的其他 ViewModel 并将此属性用于 rest OnNavigatedTo
代码)
public class RightDrawerViewModel : BaseViewModel {
// ..
}
public abstract class BaseViewModel : INavigationAware {
public NavigationParameters NavigationParameters { set; get; } // parameters holder
public void OnNavigatedTo(NavigationContext navigationContext)
{
if (navigationContext?.Parameters != null)
NavigationParameters = navigationContext.Parameters;
// ..
}
public void OnNavigatedFrom(NavigationContext navigationContext)
{
NavigationParameters = null;
}
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
// ..
}
IsDrawerOpen
设置为 true 之前传递参数。// 1. Let UserControl class implement an interface that has `DataContext GetRightDrawerDataContext();` method,
// 2. Inject services instnace in ctor of UserControlViewModel via Prism's Ioc Container
if (services.GetRightDrawerDataContext() is INavigationAware nv)
nv.NavigationParameters = parameters; // parameters to pass
IsDrawerOpen = true;
RightDrawerViewModel
可以从NavigationParameters
属性中获取参数。var b = NavigationParameters?.TryGetValue("Parameter1Key", out object object1Instance);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.