如何在 Xamarin XAML

问题描述

我想将 x:DataTypeBindingContext 一起使用,如下所示。

<ContentPage
    x:DataType="local:MainPageviewmodel">
    <ContentPage.BindingContext>
        <local:MainPageviewmodel />
    </ContentPage.BindingContext>

    <Label
        x:DataType="local:Titleviewmodel"
        BindingContext ="{Binding Innerviewmodel}" 
        Text="{Binding Title}" />

</ContentPage>

抱歉@Jason,我之前的模拟代码过于简化而导致误导..因此我更新了我的模拟代码,如下所示。

public class MainPageviewmodel
{
    private Titleviewmodel _innerviewmodel;
    public Titleviewmodel Innerviewmodel
    {
        get => _innerviewmodel;
        set => SetProperty(ref _innerviewmodel,value);
    }
}

public class Titleviewmodel
{
    private string _title;
    public string Title
    {
        get => _title;
        set => SetProperty(ref _title,value);
    }
}

我不使用 Innerviewmodel.Title 进行绑定的原因是 PropertyChanged 事件只检查属性路径。因此,如果我更新 Innerviewmodel.Title,它会引发 PropertyChanged 事件,路径为 "Title",而不是 "Innerviewmodel.Title"。它会导致问题。

我知道我可以像下面那样解决

public class MainPageviewmodel
{
    private void OnInnerviewmodelPropertyChanged(object sender,PropertyChangedArgs e)
    {
        // ...
        RaisePropertyChanged(this,"Innerviewmodel.Title");
    }
}

但是,我更喜欢更改 BindingContext 而不是中继 PropertyChanged 事件。


但是,由于以下原因,它构建失败。

错误 XFC0045:绑定:在“Local.Titleviewmodel”上找不到属性“Innerviewmodel”。

即使我像下面那样删除 x:DataType,仍然会失败,因为 MainPageviewmodel 没有 Title 属性

<Label
    BindingContext ="{Binding Innerviewmodel}"
    Text="{Binding Title}" />

因此,我放弃使用如下所示的 x:null 编译绑定。

<Label
    x:DataType="x:null"
    BindingContext ="{Binding Innerviewmodel}" 
    Text="{Binding Title}" />

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)