Question

I made a main window that displays various user controls in a content control. In this window, I have the user controls and their accompanying view models in the XAML as DataTemplate Resources. This window has a button that needs to display the user control in the contentcontrol and instantiate the view model for it. How can i pass the resource to my RelayCommand, so that i can tell the command which user control and view model to use? I figured out how to pass a hard-coded string as the command parameter, but now I'm wanting to pass the x:Name so i can reuse this command etc for more than one View-ViewModel.

Main Window's XAML snippets:

<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}">

... In the Main Window's ViewModel, here relevant code so far:

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]);
    }

... in other words, how do i get the name of the my DataTemplate w/ x:Key="EmployerSetup" in the XAML? If it matters, I'm using MVVMLight too

Était-ce utile?

La solution

Try using the Name property of the class Type:

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
  ...
}

I'd still say passing the DataTemplate to the VM just seems strange. I'd just have two commands and switch the command used in the Button.Style according to the conditions you got.

If you "have" to use a single RelayCommand or the world might end, I'd tend to use a static enum that you can reference from xaml for CommandParameter than pass the whole DataTemplate object.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top