简体   繁体   中英

WPF,C#: Space in Menu command

I have a WPF menu I am using, and it simply doesn't like when I have a space in the Command.

<MenuItem Command="Add to Catalog">
</MenuItem>

It always throws a nasty error when creating the view, and Visual Studio complains

Cannot resolve symbol "Add to Catalog".

If I have a single piece of text with no whitespace, it works fine. Any help is greatly appreciated.

You're binding Command to some method. C# doesn't allow to use spaces in method's or variable names. So why should XAML allow you to use spaces when your method name look like 'AddtoCatalog' or 'Add_to_Catalog'? You just binding it to non-existing method.

Probably you want to set Header name for menu item? There you can have spaces. Here is example:

<MenuItem Header="Add to Catalog" Command="{Binding Add_to_Catalog}"/>

*where Add_to_Catalog is your method name.

First of you need to bind the command to a CommandBinding, something like this.

<Window.CommandBindings>
    <CommandBinding Command="AddToCatalog" CanExecute="AddToCatalog_CanExecute" Executed="AddToCatalog_Executed" />
</Window.CommandBindings>

Now you can easily use the command as such

<MenuItem Command="AddToCatalog" Header="Add to Catalog">
</MenuItem>

Notice that the header is different. That is the text that is visible in the menu.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM