开发者

MVVM Binding grid to different types of EntitySets (selected from combobox)

I'm trying to get my head round MVVM, and have a fairly simple requirement that i'm struggling with.

I'm using RIA services, and in my model, i've got 3 entities that represent views from a DB.

In my XAML view at the moment, I have a combobox which allows the user to select a particular view from the DB, 开发者_Go百科and I have a datagrid that should display the results from the users selection. The problem I am having, is that the DomainContext.Load method (called when the user selects an item from the ComboBox) returns an EntitySet of a specific type (I.E EntitySet<Servers> or EntitySet<Apps>), depending on which view is selected.

I need to bind the grid to a property in my ViewModel, but can't declare just one property to hold the EntitySet from the Load operation, as each Load operation returns a different type of EntitySet (<Apps>,<Servers> for instance).

Is there a generic type that I can bind my grid to, and also convert the EntitySets to?

Or, am I doing this completely wrong? All suggestions welcome as i'm floundering :)

Thanks

Mick


Use 2 different DataGrid controls (one for Apps and one for Servers) and hide/show when needed. Chances are you may want to customise them independently anyway.

Never overcomplicate things, e.g. by sharing controls, just because the GUI elements appear similar. Think of them as a ServerDataGrid control and AppDataGrid control.


Expose a property on your view model that manages the list of items you want displayed:

public class MainViewModel
{
  public INotifyPropertyChanged ListVM { get; private set; }

  public SetList()
  {
    if(whatever)
      ListVM = new ServerListViewModel(myServers);
    else
      ListVM = new AppListViewModel(myApps);

    OnPropertyChanged("ListVM");
  }
}

Bind a ContentPresenter or ContentControl to this property. Define DataTemplates to have WPF resolve the correct view that displays the appropriate DataGrid:

<UserControl
  x:Class="Foo.MainView"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:myNS="clr-namespace:Foo"
  >

  <UserControl.Resources>
    <DataTemplate DataType="{x:Type myNS:ServerListViewModel}">
      <myNS:ServerListView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type myNS:AppListViewModel}">
      <myNS:ServerListView />
    </DataTemplate>
  </UserControl.Resources>

  <ContentPresenter Content="{Binding ListVM}" />
</UserControl>

As you populate that ListVM property with different view models, WPF will automatically resolve the correct view based on the DataTemplates you define. Of course you wouldn't want to tightly couple your view to your VMs by definining the data templates in the control as I showed above, so put them where it makes the most sense for you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜