Xamarin绑定DataContext对象Path =。强制性升级

时间:2018-08-08 15:05:08

标签: xamarin.forms label converter datacontext

我有一个具有以下两个属性的viewmodel:

public class MyViewModel : INotifyPropertyChanged
{
    protected string _aaa;
    protected string _bbb;

    public string AAA
    {
        get { return _aaa; }
        set
        {
            _aaa = value;
            RaisePropertyChanged(nameof(AAA));
        }
    }
    public string BBB
    {
        get { return _bbb; }
        set
        {
            _bbb = value;
            RaisePropertyChanged(nameof(BBB));
        }
    }

 /// etc.…..
}

我还有一个视图,其出价上下文是MyViewModel类型的对象:

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

         <Label Grid.Row="0" x:Name="Label1" Text="{Binding AAA}" />
         <Label Grid.Row="1" x:Name="Label2" Text="{Binding Path=. , Converter={StaticResource MyConverter}}" />
 </Grid>

并且转换器同时使用属性AAA和BBB返回字符串值。

初始化时一切正常。当AAA属性更改时,label1相应地更改其值,但是如果AAA或BBB更改,我也需要通过调用转换器来强制Label2更新其值。但是由于绑定是直接通过数据上下文(Path =。)而不是其属性之一完成的,因此实际上它从未更新其text属性。

有人知道如何解决我的铅吗? 预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在视图模型中添加一个属性,例如Self,该属性返回对其自身实例的引用;并确保在更新AAABBB时引发相同的属性更改事件。

public class MyViewModel : INotifyPropertyChanged
{
    protected string _aaa;
    protected string _bbb;

    public string AAA
    {
        get { return _aaa; }
        set
        {
            _aaa = value;
            RaisePropertyChanged(nameof(AAA));
            RaisePropertyChanged(nameof(Self));
        }
    }
    public string BBB
    {
        get { return _bbb; }
        set
        {
            _bbb = value;
            RaisePropertyChanged(nameof(BBB));
            RaisePropertyChanged(nameof(Self));
        }
    }

    public MyViewModel Self
    {
        get { return this; }
    }

 /// etc.…..
}

现在,您可以将XAML更改为以下内容:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

     <Label Grid.Row="0" x:Name="Label1" Text="{Binding AAA}" />
     <Label Grid.Row="1" x:Name="Label2" Text="{Binding Path=Self, Converter={StaticResource MyConverter}}" />
</Grid>