[C#][MAUI]DesignInstanceをMAUIのXAMLで設定する / Setting WPF DesignInstance with XAML in MAUI

C#

WPFやXamarinで便利なDesignInstanceだけれど、MAUIで全く同じものはない。

だけど、d:DataContext={d:DesignInstance }をMAUIで設定するには、x:DataTypeを使用するとできるみたい。

試しに、XAML側のBindingでViewModelのプロパティ(WelcomeText)がインテリセンスに表示されるか試してみた。

C#
using CommunityToolkit.Mvvm.ComponentModel;

namespace SampleMaui.Sample;

internal class SampleViewModel : ObservableObject
{
    private string welcomeText;

    public SampleViewModel()
    {
        this.WelcomeText = "Welcome to .NET MAUI!";
    }

    // Biding target
    public string WelcomeText
    {
        get => this.welcomeText;
        set => this.SetProperty(ref this.welcomeText, value);
    }
}
XAML
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:SampleMaui.Sample"
             x:Class="SampleMaui.Sample.SampleView"
             x:ClassModifier="internal"
             Sets view-model to x:DataType
             x:DataType="local:SampleViewModel">
    <VerticalStackLayout>
        <Label 
            Text="{Binding }"
            VerticalOptions="Center" 
            HorizontalOptions="Center" />
    </VerticalStackLayout>
</ContentView>

Label.TextのBindingを入力してみると、インテリセンス表示された!

コメント

タイトルとURLをコピーしました