DataTemplate in Resource sets ViewModel to View, but then

前端 未结 3 1822
暖寄归人
暖寄归人 2021-01-06 04:53

I am trying to figure the many different ways of setting datacontext of a view to a viewmodel.

One I\'m oggling at this moment goes something like this:

I ha

相关标签:
3条回答
  • 2021-01-06 05:05

    That is the way you can enable ViewSwitching navigation in your MVVM application.

    The other missing bits are: in the view ->

    <ContentControl Content="{Binding CurrentPage}" />
    

    in the ViewModel -> (pseudo code)

    Prop ViewModelBase CurrentPage.
    

    note however that if all u want is to connect a ViewModel to a View, you can just drop the entire DataTemplate-ContentControl thing altogether, and just do this.DataContext = new SomeViewModel(); in the codebehind.

    The cleanest way I know to connect VM to Views is by using the ViewModelLocator pattern. Google ViewModelLocator.

    0 讨论(0)
  • 2021-01-06 05:09

    There are a couple of simple ways to just bind a ViewModel to a view. As Elad mentioned you can add it in the code-behind:

    _vm = new MarketIndexVM();
    this.DataContext = _vm;
    

    or, you can specify the ViewModel as a resource in your XAML of your view:

    <UserControl.Resources>
        <local:CashFlowViewModel x:Key="ViewModel"/>
        <Converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
    </UserControl.Resources>
    

    and bind the DataContext of your LayoutRoot to that resource:

    <Grid x:Name="LayoutRoot" DataContext="{StaticResource ViewModel}">
    
    0 讨论(0)
  • 2021-01-06 05:12

    Maybe this doesn't directly answer your question, but have you looked at using an MVVM framework? For example, in Caliburn.Micro you would do (very basic example):

    public class ShellViewModel : Conductor<IScreen>
    {
      public ShellViewModel()
      {
        var myViewModel = new MyViewModel();
        this.ActivateItem(myViewModel);
      }
    }
    

    ShellView.xaml

    <Grid>
      <ContentControl x:Name="ActiveItem" />
    </Grid>
    

    MyView.xaml

    <Grid>
      <TextBlock>Hello world</TextBlock>
    </Grid>
    

    This is a viewmodel first approach.

    0 讨论(0)
提交回复
热议问题