Xamarin XAML 到 C# 数据触发器

Xamarin XAML to C# Data Trigger

关于下面这个问题,我 XAML 正在工作,但正在努力转换为 C#

Xamarin / MAUI XAML to C#

我的尝试无效,我不确定为什么...我的目标是当 LayoutState.Success 它通过 VenuePageViewModel 更新时,VenueSuccessContentView 应该显示在里面页面上的 cvWrap ContentView

public partial class VenuePageViewModel : ObservableObject
{
    [ObservableProperty]
    private LayoutState layoutState = LayoutState.Loading;

    public VenuePageViewModel()
    {
        LayoutState = LayoutState.Success;
    }
}

public class VenueSuccessContentView : ContentView
{
    public VenueSuccessContentView()
    {
        Content = new Label() { Text = "hello world", TextColor = Colors.Red };
    }
}

public class MainPageCS : ContentPage
{
    public MainPageCS()
    {
        BindingContext = new VenuePageViewModel();

        var venueSuccessCV = new VenueSuccessContentView();
        Resources.Add(nameof(LayoutState.Success), venueSuccessCV);

        var cvWrap = new ContentView();
        var cv = new ContentView();
        cvWrap.Content = cv;

        Content = cvWrap;

        var datatrigger = new DataTrigger(typeof(ContentView))
        {
            Binding = new Binding(source: RelativeBindingSource.TemplatedParent, path: nameof(VenuePageViewModel.LayoutState)),
            Value = LayoutState.Success,
            Setters = {
                new Setter { Property =  ContentView.ContentProperty, Value = venueSuccessCV },
            }
        };

        cvWrap.Triggers.Add(datatrigger);
    }
}

最小回购:https://github.com/aherrick/DataTriggerCSharpMaui

DataTrigger 中的绑定路径不正确。

修改DataTrigger的Binding 属性如下。

Binding = new Binding( path: nameof(VenuePageViewModel.LayoutState))