开发者

WPF Command bindings - how can I get to event handlers

开发者 https://www.devze.com 2023-02-01 06:21 出处:网络
Hi Is there any way to choose from where XAML should use command bindings event handlers? I added copule of command binding to my cusotm control, however functions which are resonsible for execute and

Hi Is there any way to choose from where XAML should use command bindings event handlers? I added copule of command binding to my cusotm control, however functions which are resonsible for execute and can_execute are not directly in code开发者_如何学编程 behind but in another class. This class is derived from Canvas and I create instance of this class in XAML.

<s:MyCanvas  Focusable="true"  Background="Transparent" x:Name="OwnCanvas" FocusVisualStyle="{x:Null}" ScrollViewer.CanContentScroll="True" >

I add command bindings this way

<UserControl.CommandBindings>
    <CommandBinding Command="{x:Static ApplicationCommands.Copy}" CanExecute="event handler from object OwnCanvas" />
</UserControl.CommandBindings>

Is there any way to do that ? Or I have to transfer event handler directly to codebehind ??


I think you're gonna have to transfer the handler in codebehind as I don't think that's possible. I could be wrong and would love to be corrected if it is possible though.

What I usually do is just define the CommandBinding in your MyCanvas class (code behind) and then reference that MyCanvas as the CommandTarget in the custom control. Like this:

    public MyCanvas()
    {
        ...

        CommandBindings.Add(
            new CommandBinding(ApplicationCommands.Copy,
                (sender, e) => {
                    // Execute Stuff
                },
                (sender, e) => {
                    e.CanExecute = true; 
                    e.Handled = true; 
                }));
        ...
    }

And in your custom control (given it lies within the visual tree of MyCanvas)...

<Button Command="{x:Static ApplicationCommands.Copy}" CommandTarget="{Binding RelativeSource={RelativeSource AncestorType={x:Type s:MyCanvas}}}"/>

With your CommandTarget set up like that the Execute and CanExecute methods will be called on it.

0

精彩评论

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