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