开发者

How do you wire up views in Silverlight and MVVM using a TreeView?

I am building a Silverlight app which comprises a TreeView of menu options in a lefthand column and a ContentView in a righthand column. The idea is that the SelectedItemChanged event of the TreeView will change the view in the content area.

What is the 'purest MVVM' way of achieving this?

My idea is to have a TreeMenuView and TreeMenuViewModel for managing the menu events, but after that I'm a bit lost. I could use an EventAggregator to send a message from the TreeMenuViewModel to a `ContentViewModel' that would then set its current Co开发者_如何学编程ntentView based on the message args- but surely that breaks MVVM, in the sense that a ViewModel shouldn't know about UI constructs like a View?

Am I missing something simple here?

How does a ViewModel layer drive the View selection?


I would create a ShellViewModel which had:

  • ObservableCollection<ViewModelBase> AvailablePages
  • int SelectedPageIndex
  • ViewModelBase CurrentPage, which returns AvailablePages[SelectedPageIndex]

Your ShellView can be anything you want. If you want to display your AvailablePages in a TreeView, then go ahead. Just remember to bind SelectedIndex to `SelectedPageIndex

In your case, I would create a DockPanel with a TreeView on the Left bound to AvailablePages, and a ContentControl on the right with ContentControl.Content bound to CurrentPage

Edit

Here's an example

<DockPanel>
    <TreeView DockPanel.Dock="Right"
              ItemsSource="{Binding AvailablePages}"
              SelectedItem="{Binding SelectedPageIndex}">
    ...
    </TreeView>

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

Then use DataTemplates to define how the ContentControl containing CurrentPage will look

<Window.Resources>
    <DataTemplate DataType="{x:Type local:HomePageViewModel}" />
         <local:HomePageView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type local:CustomerViewModel}" />
         <local:CustomerView />
    </DataTemplate>
</Window.Resources>


Ok I give it a shot

in TreeMenuViewModel:

public string PropSelectedItem
{
get;
set;
}

in TreeMenuView:

<TreeView Context="{Binding TreeMenuViewModel}" Content="{Binding PropSelectedItem, Mode=OneWayToSource}"/>

in ContentViewModel:

public ViewModelBase PropSelectedItem
{
get
 {
switch(TreeMenuViewModelStatic.PropSelectedItem)
{
  case "Booo": return typeof(View1);
  case "Foo": return typeof(View2);
}


  }
private set;
}

in ContentView:

<ContentControl Context="{Binding TreeMenuViewModel}" Content="{Binding PropSelectedItem, Mode=OneWay}"/>

and you need a value convertor here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜