You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI导航视图二级绑定报错求助:切换子项数据类型后崩溃

问题原因与解决方案

你遇到的System.ArgumentException是因为错误地将DataTemplate直接放入NavigationViewItem.MenuItems集合中。MenuItems是用于存放具体菜单项对象的集合,而子项的模板需要通过MenuItemTemplate属性来指定,与MenuItemsSource配合使用。

修正后的代码

<DataTemplate x:Key="NavigationViewMenuItem" x:DataType="local:Category">
    <NavigationViewItem Content="{x:Bind Name}" 
                        MenuItemsSource="{x:Bind Cars}">
        <!-- 用MenuItemTemplate指定子项的渲染模板 -->
        <NavigationViewItem.MenuItemTemplate>
            <DataTemplate x:DataType="local:Car">
                <NavigationViewItem Content="{x:Bind CarName}"/>
            </DataTemplate>
        </NavigationViewItem.MenuItemTemplate>
    </NavigationViewItem>
</DataTemplate>

关键说明

  • 原来的代码中,NavigationViewItem.MenuItems被错误地填充了DataTemplate,但该属性的预期是菜单项实例(如NavigationViewItem),而非模板,这直接导致了参数异常。
  • 改用MenuItemTemplate属性后,当MenuItemsSource="{x:Bind Cars}"绑定到Car集合时,框架会自动使用指定的DataTemplate渲染每个Car对象,生成对应的子菜单项。

额外检查项

  1. 确保Category类中的Cars属性是**ObservableCollection<Car>类型**(而非普通List<Car>),这样集合变化时UI能自动更新。
  2. 确保Car类的CarName属性是公共可访问的,若需要响应属性变更,需实现INotifyPropertyChanged接口。

内容的提问来源于stack exchange,提问作者Webbert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:50:27