【发布时间】:2011-07-01 13:46:57
【问题描述】:
我正在尝试创建一个包含 ListBox 的视图,该 ListBox 的 ItemsSource 属性绑定到 ObservableCollection 并且其 ItemTemplate 属性绑定到另一个属性。我知道不清楚,所以我会添加一些代码......
此代码是我的标记中的相关部分:
<ListBox ItemsSource="{Binding MyCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Content="{Binding FirstName}" Height="{Binding Path=Index, RelativeSource={RelativeSource AncestorType={x:Type local:MainWindowViewModel}}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
('FirstName'是Person类型的一个属性,是我的集合的类型参数,这个类的代码我就不加了,因为很直观) 视图的代码隐藏设置 DataContext 来保存对这个 ViewModel 类的引用和实例:
public class MainWindowViewModel : INotifyPropertyChanged
{
int index;
ObservableCollection<Person> myCollection;
public ObservableCollection<Person> MyCollection
{
get
{
if (myCollection == null)
{
//create the collection - not relevant for my question
}
return myCollection;
}
}
public int Index
{
get
{
//calculate value...
}
set
{
//set the value...
}
}
由于我将 ItemsSource 绑定到集合,我发现很难绑定到 ViewModel 中的属性(我设法简单地绑定 Person 的属性...),并且我的代码在输出窗口中出现绑定错误:
找不到与引用“RelativeSource FindAncestor, AncestorType='SimpleMVVM.MainWindowViewModel', AncestorLevel='1'' 进行绑定的源。绑定表达式:路径=索引;数据项=空;目标元素是 'Button' (Name='');目标属性是“高度”(类型“双”)
有人可以帮我解决这个问题吗? (顺便说一句 - 抱歉标题不好,我只是找不到更清晰的内容)
【问题讨论】:
标签: wpf data-binding mvvm