WinUI NavigationView MenuItemTemplate抛出InvalidCastException异常
问题原因
当使用x:Bind配合指定x:DataType的DataTemplate渲染NavigationView菜单项时,NavigationView内部处理子菜单(Children集合)时会将自定义MenuItem对象包装为WinRT.IInspectable类型,而编译时绑定的x:Bind无法自动完成该类型转换,从而抛出InvalidCastException。
解决方案
方案1:替换x:Bind为Binding
改用运行时绑定的Binding替代编译时绑定的x:Bind,可自动处理类型包装问题:
<Page.Resources> <DataTemplate x:Key="NavigationViewMenuItem" DataType="local:MenuItem"> <NavigationViewItem Content="{Binding Name}" MenuItemsSource="{Binding Children}"/> </DataTemplate> </Page.Resources>
方案2:保留x:Bind并完善MenuItem类
若要保留x:Bind的编译时检查优势,需让MenuItem实现INotifyPropertyChanged接口,并调整x:Bind的绑定模式:
第一步:修改MenuItem类实现接口
using System.ComponentModel; using System.Runtime.CompilerServices; public class MenuItem : INotifyPropertyChanged { private string _name; private string _tag; private IEnumerable<MenuItem> _children; public string Name { get => _name; set { _name = value; OnPropertyChanged(); } } public string Tag { get => _tag; set { _tag = value; OnPropertyChanged(); } } public IEnumerable<MenuItem> Children { get => _children; set { _children = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
第二步:调整DataTemplate的x:Bind模式
<Page.Resources> <DataTemplate x:Key="NavigationViewMenuItem" x:DataType="local:MenuItem"> <NavigationViewItem Content="{x:Bind Name, Mode=OneWay}" MenuItemsSource="{x:Bind Children, Mode=OneWay}"/> </DataTemplate> </Page.Resources>
额外注意事项
- 确保
MenuItem类为public访问修饰符,且XAML中local命名空间正确指向该类所在的程序集与命名空间。 - 若使用
ObservableCollection作为Children类型,其自带INotifyCollectionChanged实现,可确保集合变更时UI同步更新。
内容的提问来源于stack exchange,提问作者Key
相关产品推荐
相关产品推荐

