定义可观察对象
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进行了绑定。