代码创建的DataTemplate中的VisualStateManager

问题描述 投票:0回答:1
c# xaml maui visualstatemanager
1个回答
0
投票

感谢

Liqun Shen-MSFT
在评论中发布的链接,我可以让它工作。这是
DataTemplate
代码:

private static DataTemplate DefaultItemTemplate => new( () => {
    var view = new Border() {
        Stroke = Colors.Transparent,
        StrokeThickness = 4d,
        BackgroundColor = Colors.WhiteSmoke,
        StrokeShape = new RoundRectangle { CornerRadius = 4 },
        MinimumWidthRequest = 36,
        MinimumHeightRequest = 36,
    };
    var label = new Label() {
        Text = "-",
        TextColor = Colors.Black,
        FontSize = 14,
        HorizontalOptions = LayoutOptions.Center,
        VerticalOptions = LayoutOptions.Center
    };
    view.Content = label;

    // using Microsoft.Maui.Controls.Internals;
    // this make the magic, you need to set the namescope and register the name this way
    INameScope nameScope = new NameScope();
    NameScope.SetNameScope(view, nameScope);
    //nameScope.RegisterName("Root", view);
    nameScope.RegisterName("Index", label);


    var commonStateGoup = new VisualStateGroup { Name = "CommonStates" };
    var stateNormal = new VisualState { Name = "Normal" };
    var stateSelected = new VisualState { Name = "Selected" };

    stateNormal.Setters.Add(new());

    stateSelected.Setters.Add(new Setter {
        //TargetName = "Root",
        Property = BackgroundColorProperty,
        Value = Application.Current!.Resources.TryGetValue("Primary",out var primaryColor) ? (Color)primaryColor : Colors.BlueViolet,
    });
    stateSelected.Setters.Add(new Setter {
        TargetName =  "Index",
        Property = Label.TextColorProperty,
        Value = Colors.White,
    });

    commonStateGoup.States.Add(stateNormal);
    commonStateGoup.States.Add(stateSelected);

    VisualStateManager.GetVisualStateGroups(view).Add(commonStateGoup);

    return view;
});
© www.soinside.com 2019 - 2024. All rights reserved.