从 ViewModel 设置 UserControl 中的 DataContext
我有一个包含列表框的视图。我将其命名为 CityListingPage.xaml。这个列表页面有一个 CityListingViewModel,它与视图绑定,有点像这样:
DataContext="{Binding CityListing, Source={StaticResource Locator}}"
这很好用。现在我要将页面更改为透视控件,其中透视项将是 CityListingViewModel 的实例,但显然使用不同的构造函数数据(即国家/地区),
我将 ListBox 提取到 UserControl 中。现在我正在努力如何完成这项工作,以便对于每个列表我都能获得 CityListingViewModel 的新实例。
我尝试在 ViewModelLocator 中创建 CityListingViewModel 的集合,但如何将 CityListingViewModel 实例传递给 UserControls DataContext?
也许有一种不同的、更好的方法来做到这一点?
I have a View that contains a Listbox. I'll call it CityListingPage.xaml. This list page has a CityListingViewModel, that is binded with the View like somewhat like this:
DataContext="{Binding CityListing, Source={StaticResource Locator}}"
This works nicely. Now I what to change my page to a Pivot Control, where the Pivot Items, would be instances of CityListingViewModel, but obviously with different constructor data (ie. Country)
I extracted the ListBox into a UserControl. Now I'm struggling how to make this work so that for each list I get a new instance of the CityListingViewModel.
I tried creating in the ViewModelLocator a collection of CityListingViewModels but how do I pass the a CityListingViewModel instance to the UserControls DataContext?
Perhaps there is a different, better way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在没有看到您的代码的情况下,我将做一些猜测,但我认为您可以直接通过数据绑定来完成。由于每个数据透视项都获取 CityListingViewModel 的实例,因此您可以将该绑定传递给 UserControl:
如果您发布更多代码来显示您正在尝试执行的操作,我们可能会提供更多帮助。
Without seeing your code, I'm going to do a little guessing, but I think you can do it directly via data binding. Since each pivot item is getting an instance of CityListingViewModel, you can just pass that binding along to the UserControl:
If you post a little more code showing what you're trying to do, we might be able to be of more help.
以下是使用集合创建全景页面的两个答案。但我非常确定该方法可以适用于数据透视页面:
第二篇文章应该更相关。
The following are two answers for using a collection to create panorama pages. But I am quite sure that the approach can be adapted to pivot pages:
The second post should be more relevant.
如果您正在考虑将相同的数据分区到数据透视表页面上的多个视图上,那么我建议不要使用多个视图模型,特别是如果您用于所有数据的数据源相同。
只需有一个每个视图将绑定到的参数,并使用 Linq 来控制该参数可见的数据。
因此,您将拥有一个变量,其中包含要显示的所有数据以及查询该数据的每个视图的一个参数。
If you are thinking of partitioning the same data over multiple views on a pivot page then I would suggest NOT using several view models, especially if it is the same datasource you are using for all the data.
Simply have a parameter which each view would bind to and use Linq to control what data is visible to that parameter.
So you will have the variable which will contain all the data to be displayed and one parameter per view querying that data.