CommunityToolkit.Mvvm —— 创建可观察对象

文章介绍了在MaUI应用中如何使用ObservableObject和ObservableProperty特性来创建可观察的ViewModel,以及如何将ViewModel与ContentPage的内容进行数据绑定,特别是通过示例展示了如何定义和使用ObservableProperty来自动生成getter和setter方法,以更新界面上的WebView链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ObservableObject
ObservableProperty

定义可观察对象

public partial class IntroductionViewModel : ObservableObject
{
    /// <summary>
    /// URL
    /// </summary>
    [ObservableProperty]
    private string _introductionWebViewUrl = "https://www.baidu.com";
}

私有属性【_introductionWebViewUrl】标记为【ObservableProperty】,会自动生成如下代码:

public string? IntroductionWebViewUrl
{
    get => _introductionWebViewUrl;
    set => SetProperty(ref _introductionWebViewUrl, value);
}

使用可观察对象

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewModels="clr-namespace:SoradasRainRadar.ViewModels"
             x:Class="SoradasRainRadar.Views.IntroductionPage"
             NavigationPage.HasNavigationBar="False"
             Title="IntroductionPage">
    <ContentPage.BindingContext>
        <viewModels:IntroductionViewModel/>
    </ContentPage.BindingContext>
    <!--ウェブビュー-->
</ContentPage>
((IntroductionViewModel)BindingContext).IntroductionWebViewUrl

上面ViewModel和ContentPage进行了绑定。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值