Xamarin.Forms中的XAML页面中未绑定值

eit6fx6z  于 2023-03-06  发布在  其他
关注(0)|答案(1)|浏览(201)

我有一个文本是动态变化的,需要在用户界面中更新,但它没有绑定。
下面是视图模型:

internal class PowerViewModel : INotifyPropertyChanged
{
    public string Power { get; set; }
    
    public PowerViewModel()
    {  
        MessagingCenter.Instance.Subscribe<App, string>(this, "power_topic", OnPowerChanged);
    }
    
    public event PropertyChangedEventHandler PropertyChanged;
    
    private void OnPowerChanged(App app, string power)
    {
        Power = power;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Power)));
    }
}

方法OnPowerChanged()被触发并且Power取一个值。
视图代码和绑定如下:

namespace IotApp.Views
{
    public partial class ItemDetailPage : ContentPage
    {
        public ItemDetailPage()
        {
            InitializeComponent();
            BindingContext = new PowerViewModel();
            BindingContext = new ItemDetailViewModel();
        }
    }
}

下面是XAML代码:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:viewmodels="clr-namespace:IotApp.ViewModels" x:DataType="viewmodels:PowerViewModel"
             x:Class="IotApp.Views.ItemDetailPage">
    <ContentPage.BindingContext>
        <viewmodels:PowerViewModel />
    </ContentPage.BindingContext>
    
    <ContentPage.Background>
        <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
            <GradientStop Color="#faeee2" Offset="0.1"/>
            <GradientStop Color="#a0bec6" Offset="0.5"/>
        </LinearGradientBrush>
    </ContentPage.Background>
        
    <Shell.TitleView>
        <StackLayout Orientation="Horizontal">
            <Label Text="Home" FontSize="16"/>
            <Image Source="logo_white" VerticalOptions="EndAndExpand" HorizontalOptions="EndAndExpand"/>
        </StackLayout>
    </Shell.TitleView>
    
    <StackLayout Spacing="20" Padding="15" VerticalOptions="Start">
    
        <Label Text="{Binding Power}"  FontSize="18" TextColor="#1c2d57" />
    
    </StackLayout>
    
</ContentPage>

它应该显示Power的值,但是一直是空的,我不知道为什么。请帮帮忙。
非常感谢。

ia2d9nvy

ia2d9nvy1#

问题

问题是您要多次设置BindingContext
在此设置两次:

namespace IotApp.Views
{
    public partial class ItemDetailPage : ContentPage
    {
        public ItemDetailPage()
        {
            InitializeComponent();
            BindingContext = new PowerViewModel();
            BindingContext = new ItemDetailViewModel();
        }
    }
}

第三次在这里:

<ContentPage.BindingContext>
    <viewmodels:PowerViewModel />
</ContentPage.BindingContext>

代码隐藏中的第二个赋值优先,因此您实际上是在尝试绑定到错误的ViewModel。

溶液

删除XAML中BindingContext的赋值,同时删除后面代码中的第二个赋值,使代码如下所示:

namespace IotApp.Views
{
    public partial class ItemDetailPage : ContentPage
    {
        public ItemDetailPage()
        {
            InitializeComponent();
            BindingContext = new PowerViewModel();
        }
    }
}

相关问题