开发者

How to implement Command with Tooltip in MVVM?

开发者 https://www.devze.com 2023-04-02 11:54 出处:网络
Most MVVM frameworks implement basic Command pat开发者_如何学Pythontern (for example DelegateCommand in PRISM), that uses Execute and CanExecute methods from ViewModel.

Most MVVM frameworks implement basic Command pat开发者_如何学Pythontern (for example DelegateCommand in PRISM), that uses Execute and CanExecute methods from ViewModel.

Hovewer, I often need to add a tooltip to the command. For example, I want to describe the purpose of a command or explain, why it has been disabled.

Currently my tooltips are independent, but this results in code duplication of style definitions.

Is there a way to integrate tooltips with the MVVM Command pattern?

Should I create my own Command class, or is it considered bad practice?


I think your question is perfectly valid. I'm not aware of such a command. RoutedUICommand is the closest I can think of, but it's obviously routed (no good for MVVM) and only defines a Text property - no ToolTip.

As you've hinted, you could certainly define your own. Alternatively, you could define some kind of command registration service, whereby modules register ICommand implementations along with metadata about that command (including the tooltip).


Why not just extend PRISM's 'Delegate Command' and add a ToolTip property?

public class DelegateCommandEx : DelegateCommand 
{
    public string ToolTip { get; set; }
}

I believe by default WPF commands don't have that property because a ToolTip doesn't have to be a string in WPF - it can be an object, a control, a group of controls, etc


An ICommand is a way to bind to events raised by the UI in MVVM. It doesn't have a ToolTip property, and I don't see how this is useful as the command is acting as a handler and has no UI. Are you referring to a ToolTip specific Command in which case it does make sense?

Generally you would use the ToolTipService with WPF.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号