简体   繁体   中英

Binding UserControl(s) to a ListView

I have the following in C# and VS2010:

- a MainWindow.xaml with a ListView
- a MainViewModel with an ObservableCollection of objects of type, UnitData
- a UnitDataDisplay.xaml with a bunch of labels tied to members of UnitData

I need to show a variable number of UnitDataDisplays in my ListView that should be based on MainViewModel's ObservableCollection of UnitDatas. What exactly should the syntax be in XAML to bind the ListView Items to multiple UserControl objects without breaking the MVVM separation of concerns? I mean I could easily have my ObservableCollection contain a bunch of UnitDataDisplay objects but that would force my MainViewModel to have knowledge of View details.

My MainWindow XAML file looks like this:

<Window x:Class="ListViewTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="350">
    <Grid>
        <ListView Height="234" HorizontalAlignment="Left" Margin="12,28,0,0" Name="listView1" VerticalAlignment="Top" Width="304" ItemsSource="{Binding Path=UnitDataDisplay}"/>
    </Grid>
</Window>

Any help would be greatly appreciated.

A common approach is to use implicit data templates based on model type ( UnitData ):

<Window.Resources>
   <DataTemplate DataType="{x:Type local:UnitData}">
      <local:UnitDataDisplay />
   </DataTemplate>
</Window.Resources>

I would then change your ListView to a ListBox , or an ItemsControl if you don't want each item in the list to be selectable.

I would also seriously consider using an MVVM framework rather than the above approach, such as Caliburn.Micro which makes view composition such as this much easier, as well as a host of other advantages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM