开发者

Ctrl-Shift-Plus keyboard shortcut and WPF listview

In a typical Windows forms list view the shortcut key Ctrl + Shift + + resizes all the columns in the grid to their "automatic" size (as they would be if you double clicked on the resize handle in the开发者_JS百科 column header).

In my WPF application containing a list view the same shortcut doesn't work.

  1. Anyone know why this is?
  2. More importantly - is there an easy way to add this functionality to all grids in my application?


1 - In windows forms columns are hard-coded into the ListView, in WPF there is no guarantee that there even will be any so it makes not much sense to include that hotkey which would only work if one specific ListView.View is used.

2 - The apply-to-all part might be a bit roundabout with behaviors but here is the behavior method:

<ListView>
    <i:Interaction.Behaviors>
        <b:AutoSizeColumnsKeyboardShortcutBehavior />
    </i:Interaction.Behaviors>
    <!-- ... -->
</ListView>
public class AutoSizeColumnsKeyboardShortcutBehavior : Behavior<ListView>
{
    public class AutoSizeColumnsCommand : ICommand
    {
        public bool CanExecute(object parameter)
        {
            var target = parameter as ListView;
            if (target == null) return false;
            var view = target.View as GridView;
            return view != null;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            var target = parameter as ListView;
            var view = target.View as GridView;
            foreach (var column in view.Columns)
            {
                column.Width = double.NaN;
            }
        }
    }

    protected override void OnAttached()
    {
        base.OnAttached();
        var command = new AutoSizeColumnsCommand();
        var keybinding = new KeyBinding(command,
            new KeyGesture(Key.OemPlus, ModifierKeys.Control | ModifierKeys.Shift))
            {
                CommandParameter = this.AssociatedObject
            };
        this.AssociatedObject.InputBindings.Add(keybinding);
    }
}

You could define a global implicit style which pretty much does the exact same thing in the Loaded event of the control, that way you do not need to manually assign the behavior.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜