首页 > 解决方案 > 视图模型上的 Xamarin 绑定属性:无法识别视图模型

问题描述

我遇到了一个问题,我想将 DataTemplateSelector 用于单个项目。在这个GitHub 问题中,我遇到了一个扩展内容视图并允许这种情况发生的答案。我现在将它与两个数据模板一起使用。我传递给这些的 bindingcontext 效果很好。但是一旦我想使用另一个绑定上下文,它就会说它找不到它。

我的数据模板:

<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    xmlns:viewmodels="clr-namespace:Universal_ONE.ViewModels">
    <DataTemplate x:Key="AirpointSettingsDataTemplate">
        <StackLayout Orientation="Horizontal"
                      x:Name="StackName"
                      Spacing="10">
            <Label Text="TestAirpoint" TextColor="Black" FontSize="30" FontFamily="Roboto"/>
            <Label Text="{Binding U}" TextColor="Black" FontSize="30" FontFamily="Roboto">
                <Label.BindingContext>
                    <viewmodels:AirpointSettingsViewModel/>
                </Label.BindingContext>
            </Label>
        </StackLayout>
     </DataTemplate>
</ResourceDictionary>

视图模型:

public class AirpointSettingsViewModel : INotifyPropertyChanged
{
    public AirpointSettingsViewModel()
    {
        Debug.WriteLine("ViewModel Airpoint settings");
    }

    private string u = "sometext";
    public string U
    {
        get => u;
        set 
        {
            u = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(U)));
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;
}

在视图模型中放置断点时,它也不会命中这些断点。

我还使用视图模型作为堆栈布局的绑定上下文进行了测试,但这也无济于事。

错误:

[0:] Binding: 'U' property not found on 'Universal_ONE.ViewModels.AirpointSettingsViewModel', target property: 'Xamarin.Forms.Label.Text'

我还在随机属性上使用完全不相关的视图模型进行了测试。到时候还是找不到。因此问题不在于它找不到视图模型或它有故障。

标签: c#xamarinmvvmdata-binding

解决方案


推荐阅读