NavigationView.ClearValue(NavigationView.MenuItemsProperty) 总是抛出 System.ArgumentException

问题描述 投票:0回答:2
var temp = new NavigationView();
temp.ClearValue(NavigationView.MenuItemsProperty);

// System.ArgumentException: 'Value does not fall within the expected range.'
// Exception occurred: 'System.ArgumentException'(WinRT.Runtime.dll)
// WinRT Infomation: Argument 'source' is null.

即使 temp.ReadLocalValue(NavigationView.MenuItemsProperty) 不返回 DependencyProperty.UnsetValue,也会出现同样的结果。

如何才能达到调用SetBinding前先调用ClearValue的效果?

c# dependency-properties winui-3
2个回答
0
投票

ClearValue
不适合清除
MenuItems
控件的
NavigationView
集合,因为它旨在清除依赖属性的本地值,而不是操作集合的内容。

试试这个:

var temp = new NavigationView();
temp.MenuItems.Clear();

0
投票

首先,如果你想切换菜单项源,你需要定位

MenuItemsSourceProperty
,而不是
MenuItemsProperty

<Grid RowDefinitions="Auto,*">
    <StackPanel Orientation="Horizontal">
        <Button
            Click="MenuItemsAButton_Click"
            Content="MenuItemsA" />
        <Button
            Click="MenuItemsBButton_Click"
            Content="MenuItemsB" />
    </StackPanel>
    <NavigationView
        x:Name="NavigationViewControl"
        Grid.Row="1" />
</Grid>
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    public ObservableCollection<string> MenuItemsA { get; set; } = new()
    {
        "Menu Item 1",
        "Menu Item 2",
        "Menu Item 3",
    };

    public ObservableCollection<string> MenuItemsB { get; set; } = new()
    {
        "Menu Item 4",
        "Menu Item 5",
        "Menu Item 6",
    };

    private void BindMenuItemsTo(string menuItemsPropertyName)
    {
        if (this.NavigationViewControl.MenuItemsSource is not null)
        {
            this.NavigationViewControl.ClearValue(NavigationView.MenuItemsSourceProperty);
        }

        this.NavigationViewControl.SetBinding(
            NavigationView.MenuItemsSourceProperty,
            new Binding()
            {
                Source = this,
                Path = new PropertyPath(menuItemsPropertyName),
            });
    }

    private void MenuItemsAButton_Click(object sender, RoutedEventArgs e)
    {
        this.BindMenuItemsTo("MenuItemsA");
    }

    private void MenuItemsBButton_Click(object sender, RoutedEventArgs e)
    {
        this.BindMenuItemsTo("MenuItemsB");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.