我正在使用 C# 中的 MVVM,并试图在列表框中显示一个 View 。
我正在设置列表框项目源(在代码中,而不是在绑定(bind)和使用 View 模型集合中),然后将数据模板设置为我在 xaml 中的 View 。我遇到的问题是我的 View 始终加载其默认构造函数值,如果我从 View 中删除 datacontext 但它加载正常。
下面是我在 xaml 中创建的列表框
<ListBox Name="lbCatalogues" HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<view:CatalogueRowView/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这是我的观点的 xaml。如果我删除 DataContext 它会起作用
<UserControl.DataContext>
<model:CatalogueModel />
</UserControl.DataContext>
<Grid Name="Container" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="40" />
</Grid.ColumnDefinitions>
<!-- Catalogue_ID, UploadedTime, Client_ID, Name, Desc, Filesize -->
<Label Name="lblCatalogueID" Content="{Binding Path=CatalogueID}" Grid.Column="0"/>
<Label Name="lblUploadedTime" Content="{Binding Path=UploadedTime}" Grid.Column="1"/>
<Label Name="lblCatalogueName" Content="{Binding Path=Name}" Grid.Column="2"/>
<Label Name="lblCatalogueDescription" Content="{Binding Path=Description}" Grid.Column="3"/>
<Label Name="lblFilesize" Content="{Binding Path=Filesize}" Grid.Column="4"/>
<Grid/>
这是我设置列表框 ItemSource 的代码:
lbCatalogues.ItemsSource = catalogueViewModel.Records;
我的问题是如何让 View 在列表框中正确加载,以便列表框中的每个项目都有一个链接到该列表框 Itemsource 的 DataContext?
最佳答案
您已经知道答案:只需删除 <UserControl.DataContext>
来自你的 UserControl
您正在告诉您的 UserControl
使用 CatelogueModel
的新实例对于 DataContext
,这会覆盖任何 DataContext
这是在您使用 UserControl
时设置的.请参阅 MSDN 的列表 Dependency Property Precedence了解更多信息
我从来不建议设置 DataContext
在 UserControl
里面.它违背了 WPF 通过分离 UI 和数据层来工作的方式,并且对于任何试图使用您的 UserControl
的人来说都是一个问题。
关于链接到 ItemsSource 的 ListBox 中的每个项目的问题,DataTemplates 只是告诉 WPF 如何绘制对象。对象背后的数据仍然存在。
例如,您的列表框包含 Record
的列表对象,以及你的 DataTemplate
正在告诉 ListBox
用 CatelogueRowView
绘制每一条记录. CatelogRowView
背后的实际数据仍然是来自 catelogueViewModel.Records
的数据对象
关于WPF 列表框和 MVVM 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11508536/