.NET MAUI Uranium 2.9.1 Windows平台PickerField点击异常问题
UraniumUI PickerField Windows平台选项点击区域收缩问题解决
问题现象
在Windows平台使用UraniumUI的material:PickerField控件时,首次点击展开选项列表,所有选项的可点击区域能完整覆盖控件的整个宽度;但再次点击展开后,选项的可点击区域会收缩,仅在靠近选项文本的区域点击才能触发选中操作,无法保持全宽可点击。
复现代码
XAML代码
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:uranium="http://schemas.enisn-projects.io/dotnet/maui/uraniumui" x:Class="MyUraniumProject.MainPage" Shell.NavBarHasShadow="True" xmlns:material="http://schemas.enisn-projects.io/dotnet/maui/uraniumui/material"> <StackLayout Margin="20"> <material:PickerField HorizontalOptions="FillAndExpand" ItemsSource="{Binding List}"/> <material:PickerField HorizontalOptions="FillAndExpand" ItemsSource="{Binding List}"/> </StackLayout> </ContentPage>
后台C#代码
namespace MyUraniumProject { public partial class MainPage : ContentPage { public ObservableCollection<string> List { get; set; } public MainPage() { InitializeComponent(); List = new ObservableCollection<string>() { "a", "b", "c", "d" }; BindingContext = this; } } }
解决方案
方案1:自定义ItemTemplate强制选项占满宽度
通过为PickerField指定自定义的ItemTemplate,让每个选项的布局控件设置HorizontalOptions="FillAndExpand",确保可点击区域覆盖整个控件宽度:
<material:PickerField HorizontalOptions="FillAndExpand" ItemsSource="{Binding List}"> <material:PickerField.ItemTemplate> <DataTemplate> <Label Text="{Binding}" HorizontalOptions="FillAndExpand" HorizontalTextAlignment="Start" Padding="16,12"/> <!-- 可根据需要调整内边距,匹配UraniumUI默认样式 --> </DataTemplate> </material:PickerField.ItemTemplate> </material:PickerField>
方案2:升级UraniumUI到最新版本
该问题可能是UraniumUI旧版本在Windows平台的渲染bug,建议升级到最新版本的UraniumUI NuGet包,查看官方是否已修复该问题。
方案3:自定义Windows平台渲染器(进阶)
如果上述方案无效,可针对Windows平台自定义PickerField的渲染逻辑,调整弹出列表项的布局参数:
- 创建自定义渲染器类:
using Microsoft.Maui.Controls.Platform.Windows; using UraniumUI.Material.Controls; namespace MyUraniumProject.Platforms.Windows; public class CustomPickerFieldRenderer : PickerRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Picker> e) { base.OnElementChanged(e); if (Control != null && Element is PickerField pickerField) { // 调整Flyout中列表项的布局,确保占满宽度 var flyout = Control.Flyout as Microsoft.UI.Xaml.Controls.Flyout; if (flyout?.Content is Microsoft.UI.Xaml.Controls.ListBox listBox) { listBox.ItemContainerStyle = new Microsoft.UI.Xaml.Style(typeof(Microsoft.UI.Xaml.Controls.ListBoxItem)) { Setters = { new Microsoft.UI.Xaml.Setter(Microsoft.UI.Xaml.Controls.ListBoxItem.HorizontalContentAlignmentProperty, Microsoft.UI.Xaml.HorizontalAlignment.Stretch) } }; } } } }
- 在Windows项目的
MauiProgram.cs中注册渲染器:
builder.ConfigureMauiHandlers(handlers => { #if WINDOWS handlers.AddHandler(typeof(PickerField), typeof(CustomPickerFieldRenderer)); #endif });
内容的提问来源于stack exchange,提问作者Murilo Garrido
相关产品推荐
相关产品推荐

