带有RelativeSource问题的WPF DataBinding

时间:2011-02-21 21:08:25

标签: wpf data-binding mvvm

我正在尝试创建一个视图,该视图包含一个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''。 BindingExpression:路径=指数;的DataItem = NULL; target元素是'Button'(Name =''); target属性是'Height'(类型'Double')

有人可以帮我解决这个问题吗? (顺便说一句 - 抱歉这个糟糕的头衔,我只是找不到更清楚的东西)

2 个答案:

答案 0 :(得分:2)

Index属性将位于ListBox DataContext中,因此将Height Binding更改为以下内容并且它应该可以正常工作

Height="{Binding Path=DataContext.Index,
                 RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"/>

对于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>

答案 1 :(得分:1)

您需要将高度绑定的DataContext设置为viewmodel,就像它现在正在查找集合中各个数据项的索引属性一样

相关问题