我正在尝试创建一个包含 ListBox 的 View ,该 ListBox 的 ItemsSource 属性绑定(bind)到 ObservableCollection 并且其 ItemTemplate 属性绑定(bind)到另一个属性。我知道不清楚,所以我将添加一些代码...
此代码是我的标记中的相关部分:
<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类型的一个属性,是我的集合的类型参数。我不会添加那个类的代码,因为它很直观)
View 的代码隐藏设置 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 绑定(bind)到集合,我发现很难绑定(bind)到 ViewModel 中的属性(我设法简单地绑定(bind) Person 的属性......),并且我的代码在输出窗口中给出了绑定(bind)错误:
Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='SimpleMVVM.MainWindowViewModel', AncestorLevel='1''. BindingExpression:Path=Index; DataItem=null; target element is 'Button' (Name=''); target property is 'Height' (type 'Double')
有人可以帮我弄清楚吗?
(顺便说一句 - 抱歉标题很差,我只是找不到更清楚的东西)
最佳答案
Index 属性将位于 ListBox
DataContext 所以将高度绑定(bind)更改为以下内容,它应该可以工作
Height="{Binding Path=DataContext.Index,
RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"/>
对于列表框
<ListBox ItemsSource="{Binding MyCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Content="{Binding FirstName}"
Height="{Binding Path=DataContext.Index,
RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
关于WPF DataBinding 与 RelativeSource 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5071296/