带索引的 WPF 绑定集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16903244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:55:01  来源:igfitidea点击:

WPF Binding Collection with Index

wpfxamldata-bindingmvvm

提问by aw04

I'm trying to use a collection that is a property of another collection to bind to a listbox. The following works fine

我正在尝试使用作为另一个集合的属性的集合来绑定到列表框。以下工作正常

<ListBox ItemsSource="{Binding Path=Locations[0].Buildings}">

the problem is that I need a dynamic index and

问题是我需要一个动态索引和

<ListBox ItemsSource="{Binding Path=Locations[index].Buildings}">

where index is an integer in my viewmodel, does not work. Does anyone know how I can associate the index in my xaml with the property in my viewmodel?

其中 index 是我的视图模型中的整数,不起作用。有谁知道如何将我的 xaml 中的索引与我的视图模型中的属性相关联?

采纳答案by Reed Copsey

where index is an integer in my viewmodel, does not work. Does anyone know how I can associate the index in my xaml with the property in my viewmodel?

其中 index 是我的视图模型中的整数,不起作用。有谁知道如何将我的 xaml 中的索引与我的视图模型中的属性相关联?

One simple option would be to just expose a CurrentLocationproperty within your ViewModel, which was effectively Location[index]. You could then bind to it directly.

一个简单的选择是CurrentLocation在您的 ViewModel 中公开一个属性,这实际上是Location[index]. 然后您可以直接绑定到它。

回答by Ady

A binding within a binding is not possible, So in XAML you can't bind to "index".

绑定中的绑定是不可能的,因此在 XAML 中您不能绑定到“索引”。

a. Chris Moser'smethod, You can create a DependencyPropertythat binds to "index" Specify a change listener on the RegisterAttached handler and do your work there.

一种。Chris Moser 的方法,您可以创建一个绑定到“索引”的DependencyProperty在 RegisterAttached 处理程序上指定一个更改侦听器并在那里完成您的工作。

b. Use a Converter. You can provide index as the ConverterParameter

湾 使用转换器。您可以提供 index 作为 ConverterParameter

c. Bind to a POCO property. A POCO property would need its INotifyPropertyChanged signaled by the changer

C。绑定到 POCO 属性。一个 POCO 属性需要它的 INotifyPropertyChanged 由转换器发出信号