Wpf 如何将我的视图模型传递给用户到主视图模型?
我制作了一个主窗口,在内容控件中显示各种用户控件。在这个窗口中,我在XAML中将用户控件及其附带的视图模型作为DataTemplate资源。此窗口有一个按钮,需要在contentcontrol中显示用户控件并为其实例化视图模型。如何将资源传递给我的RelayCommand,以便告诉命令使用哪个用户控件和视图模型?我知道了如何将硬编码字符串作为命令参数传递,但现在我想传递x:Name,以便可以将此命令等用于多个视图模型 主窗口的XAML代码段:Wpf 如何将我的视图模型传递给用户到主视图模型?,wpf,mvvm,viewmodel,relaycommand,Wpf,Mvvm,Viewmodel,Relaycommand,我制作了一个主窗口,在内容控件中显示各种用户控件。在这个窗口中,我在XAML中将用户控件及其附带的视图模型作为DataTemplate资源。此窗口有一个按钮,需要在contentcontrol中显示用户控件并为其实例化视图模型。如何将资源传递给我的RelayCommand,以便告诉命令使用哪个用户控件和视图模型?我知道了如何将硬编码字符串作为命令参数传递,但现在我想传递x:Name,以便可以将此命令等用于多个视图模型 主窗口的XAML代码段: <Window.Resources>
<Window.Resources>
<!--User Controls and Accompanying View Models-->
<DataTemplate DataType="{x:Type EmployerSetupVM:EmployerSetupVM}" x:Key="EmployerSetup" x:Name="EmployerSetup">
<EmployerSetupView:EmployerSetupView />
</DataTemplate>
<DataTemplate DataType="{x:Type VendorSetupVM:VendorSetupVM}">
<VendorSetupView:VendorSetupView />
</DataTemplate>
</Window.Resources>
<Button Style="{StaticResource LinkButton}" Command="{Binding ShowCommand}" CommandParameter="{StaticResource EmployerSetup}">
。。。
在主窗口的ViewModel中,此处显示迄今为止的相关代码:
public RelayCommand<DataTemplate> ShowCommand
{
get;
private set;
}
ShowCommand = new RelayCommand<string>((s) => ShowExecuted(s));
private void ShowExecuted(DataTemplate s)
{
var fred = (s.DataType); //how do i get the actual name here, i see it when i hover with intellisense, but i can't access it!
if (!PageViewModels.Contains(EmployerSetupVM))
{
EmployerSetupVM = new EmployerSetupVM();
PageViewModels.Add(EmployerSetupVM);
}
int i = PageViewModels.IndexOf(EmployerSetupVM);
ChangeViewModel(PageViewModels[i]);
}
public RelayCommand ShowCommand
{
得到;
私人设置;
}
ShowCommand=newrelaycommand(=>ShowCommand));
已执行私有void ShowExecuted(数据模板)
{
var fred=(s.DataType);//在这里如何获取实际名称,我在使用intellisense悬停时看到它,但无法访问它!
如果(!PageViewModels.Contains(EmployerSetupVM))
{
EmployerSetupVM=新EmployerSetupVM();
添加(EmployerSetupVM);
}
int i=PageViewModels.IndexOf(EmployerSetupVM);
ChangeViewModel(PageViewModels[i]);
}
。。。
换句话说,如何在XAML中获得数据模板w/x:Key=“EmployeerSetup”的名称?如果重要的话,我也在使用MVVMLight尝试使用类的属性:
我仍然认为将DataTemplate
传递给虚拟机似乎很奇怪。我只需要两个命令,并根据您得到的条件切换按钮中使用的命令。Style
如果您“必须”使用一个
RelayCommand
或者世界末日,我倾向于使用一个静态枚举,您可以从xaml为CommandParameter
引用它,而不是传递整个DataTemplate
对象 那么这个按钮如何知道它应该通过VendorSetupVM
还是employeersetupvm
。我不理解你的问题,你的xaml和VM代码也不同步。在xaml中,您绑定到EmployerSetupCommand
,而在.cs中,我想这叫做ShowCommand
?什么是PageViewModels
,为什么您只在该函数中检查employeersetupvm
。只需清楚地键入一些您期望的伪代码。根本不知道这里面发生了什么。我真的看不出重用这么复杂的命令有什么好处。我只需要2个命令,并以按钮样式切换绑定。对不起,我进行了编辑以使命令名称正确等。我的问题是如何正确使用CommandParameter来告诉函数我应该让代码将当前视图模型更改为哪个ViewModel。PageViewModels只是ViewModels的一个集合。基本上,我只需要知道,如果我传递数据模板“EmployeerSetup”,它代表我的EmployeerSetup ViewModel,我如何在代码中获得它的名称?我现在的代码只有在使用fred.ToString()时才能获取全名
private void ShowExecuted(DataTemplate s) {
var typeName = s.DataType as Type;
if (typeName == null)
return;
var className = typeName.Name; // className will be EmployerSetupVM or VendorSetupVM
...
}