【问题标题】:Binding UserControl(s) to a ListView将 UserControl(s) 绑定到 ListView
【发布时间】:2012-11-15 23:08:13
【问题描述】:

我在 C# 和 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

我需要在我的 ListView 中显示可变数量的 UnitDataDisplay,这应该基于 MainViewModel 的 ObservableCollection 的 UnitData。 XAML 中将 ListView 项绑定到多个 UserControl 对象而不破坏 MVVM 关注点分离的语法到底应该是什么?我的意思是我可以很容易地让我的 ObservableCollection 包含一堆 UnitDataDisplay 对象,但这会迫使我的 MainViewModel 了解视图详细信息。

我的 MainWindow XAML 文件如下所示:

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

任何帮助将不胜感激。

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    一种常见的方法是根据模型类型(UnitData)使用隐式data templates

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

    如果您不希望列表中的每个项目都可选择,我会将您的 ListView 更改为 ListBoxItemsControl

    我也会认真考虑using an MVVM framework 而不是上述方法,例如Caliburn.Micro,它使这样的视图组合更容易,以及许多其他优点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2016-11-30
      • 2012-06-06
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      相关资源
      最近更新 更多