Home > Back-end >  Xamarin XAML to C# Data Trigger
Xamarin XAML to C# Data Trigger

Time:06-04

In reference to this question below I have XAML working, but am struggling with converting to C#

Xamarin / MAUI XAML to C#

Here is my attempt that isn't working and I'm not sure why... My goal is when LayoutState.Success it updated via VenuePageViewModel, VenueSuccessContentView should display inside the cvWrap ContentView on the Page.

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);
    }
}

Minimal Repo: https://github.com/aherrick/DataTriggerCSharpMaui

CodePudding user response:

The binding path is incorrect in DataTrigger .

Modify Binding property of DataTrigger as below .

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