Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xamarin 如何更改ViewCell项的值?_Xamarin_Xamarin.forms - Fatal编程技术网

Xamarin 如何更改ViewCell项的值?

Xamarin 如何更改ViewCell项的值?,xamarin,xamarin.forms,Xamarin,Xamarin.forms,我有这样一个代码: class CustomCell : ViewCell { private readonly Label _label; public static readonly BindableProperty DataProperty = BindableProperty.Create("Data", typeof(string), typeof(CustomCell), "Data"); public string Data {

我有这样一个代码:

class CustomCell : ViewCell
{
    private readonly Label _label;

    public static readonly BindableProperty DataProperty = BindableProperty.Create("Data", typeof(string), typeof(CustomCell), "Data");

    public string Data
    {
        get { return (string)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    ...

    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();

        if (BindingContext != null)
        {
                _label.Text = Data;
        }
    }
}
当我在ListView中使用此代码将值传递给它时,它工作得很好:

<customUi:CustomCell Data="{Binding Data}" />

但是,有时我希望能够从
CustomCell
本身更改
数据。当我通过编写
this.Data=“new value”来更改它时标签文本不会更改。我可以简单地编写
\u label.Text=“new value”,它可以工作,但感觉不对。另外,更改
数据
,然后调用
OnBindingContextChanged()
也感觉不对劲


正确的方法是什么?

重写
OnPropertyChanged
方法,如:

    protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        base.OnPropertyChanged(propertyName);
        if (propertyName == "Data")
            _label.Text = Data;
    }

就像您在类上创建了名为“Data”的可绑定属性一样。Label控件的属性“Text”也是可绑定的。因此,您可以对其应用相同的绑定,并且它应该可以按预期工作。 常见的模式是让控件的绑定上下文包含必要的属性,然后将各个控件的属性绑定到这些属性。 因此,与其绑定到数据属性,然后将该属性重新应用到标签,只需编辑CustomCell本身,并为标签的文本属性提供相同的绑定

<Label Text="{Binding Data}" />

您甚至可以从viewmodel中获取特定对象,并将其作为单元的绑定上下文传递,以便单元内的控件始终具有相同的绑定结构

<customUi:CustomCell BindingContext="{Binding SomeItem}" />
//Assuming SomeItem is a property inside your VM, or binding context of wherever the CustomCell is

//假设SomeItem是VM中的属性,或者是CustomCell所在位置的绑定上下文
现在,将标签的文本属性和CustomCell中任何其他控件的任何其他属性绑定到SomeItem的属性



如果您确实希望在viewcell上创建一个可绑定属性,然后将其传递给标签,那么您还可以在CustomCell的property changed事件上对其“Data”属性应用任何绑定,并对标签的Text属性应用相同的绑定。虽然实际上不需要这样做。

虽然这样做可行,但不需要手动更新text属性,这与原始海报正确宣称的“感觉不对劲”没有什么不同。改用数据绑定。查看我的回答如果我需要一些格式,例如,如果数据是十进制的,并且我希望它以某种特定的方式显示在标签中,我建议我应该使用ValueConverter,对吗?这取决于您。对于我在多个地方做的事情,我肯定会使用值转换器,是的。如果我只需要一次到位,我可能会重写on属性changed并在那里转换值,或者创建一个类型为string的helper属性来自动转换值。这一切都取决于你的偏好和你期望道具改变的频率。全局字典中的静态转换器实例是一个安全的选择。