在Xamarin Forms中,从ListView的ItemSource外部绑定数据

5

你好,我正在处理Xamarin.Forms中的问题。在ListView中出现了数据绑定问题。在模型中有一个字符串值和一个列表,该列表是ListViewItemsSource,而字符串值应该显示在每个单元格行中。

XMAL视图

<ListView ItemsSource="{Binding StudentList, Mode=TwoWay}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    <Label Text={Binding Name} />
                    <Label Text={Binding ConstantName} /> //// Not present in Itemsource. Should bind from Model. It does not render.
                 </Stacklayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

C#

public ObservableCollection<PagingButtons> _lstPagingButtons { get; set; }
public ObservableCollection<PagingButtons> lstPagingButtons
{
    get { return _lstPagingButtons; }
    set
    {
        _lstPagingButtons = value;
        OnPropertyChanged();
    }
}
string _ConstantName {get; set;} = "Xamarin";
public string ConstantName 
{
    get { return _ConstantName; }
    set { __ConstantName = value; OnPropertyChange(); 
}

我知道我可以把ConstantName添加到PagingButtons类中,但是我有30-40个类都有这种情况,这样做会很繁琐,也不是有效的方法。

2个回答

13

我假设你的ListView周围有一个ContentPage,但这可以是任何页面(甚至元素)。

给那个页面起一个名字,如果它还没有一个,就像这样:<ContentPage x:Name="MyAwesomePage" ...>

现在,把你的Label改成这样:<Label Text={Binding BindingContext.ConstantName, Source={x:Reference Name=MyAwesomePage}} />

这样,你引用了绑定到你页面的BindingContext,有效地改变了作用域。


1
你可以简单地做到:

<Label Text={Binding Source={x:Reference root}, Path=BindingContext._ConstantName}

请注意,_ConstantName 是私有字段,因此此处呈现的代码将无法正常工作。另外,我不知道 root 关键字,但这可能是我的知识缺失。 - Gerald Versluis
的确,我没有注意到这是私有的。过去我使用过类似这样的语法。 - Bruno Caceiro
很酷,我得试试。不知道那是可能的 :-) 谢谢! - Gerald Versluis
我尝试了,但它没有起作用,甚至将该字段设置为公共的。 - Rohan Sampat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接