【问题标题】:WPF RoutedCommand and CustomControl implementationWPF RoutedCommand 和 CustomControl 实现
【发布时间】:2015-03-11 14:11:49
【问题描述】:

我有一个窗口,其中有一个按钮和一个自定义控件。当我单击按钮时,CustomControl 应该做一些事情(例如动画本身)。

代码如下:

public static class Commands
{
    public static readonly RoutedCommand FooCommand = new RoutedCommand("Foo", typeof(MyCustomControl));
}

public class MyCustomControl : Control
{
    static MyCustomControl()
    {
      // Initialize as lookless control
      DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));

      // for some reason using typeof(MyCustomControl) doesn't seem to work. (not part of the same visual tree?)
      // typeof(UIElement) works, as button is a UIElement (?)
      //CommandManager.RegisterClassCommandBinding(typeof(MyCustomControl), new CommandBinding(Commands.FooCommand, OnFoo, OnCanFoo));
      CommandManager.RegisterClassCommandBinding(typeof(UIElement), new CommandBinding(Commands.FooCommand, OnFoo, OnCanFoo));
    }

    private static void OnFoo(object sender, RoutedEventArgs e)
    {
        // here I need to have the instance of MyCustomControl so that I can call myCustCtrl.Foo();
      Foo(); // <--- problem! can't access this
    }

    private static void OnCanFoo(object sender, CanExecuteRoutedEventArgs e)
    {
      e.CanExecute = true;
      e.Handled = true;
    }

    public void Foo()
    {
        // does this like:
        // this.Template.FindName(...
        // so this method can't be static
    }
}

以及我使用控件的 XAML:

<Window ...
  <!-- ... -->

<Grid>
<Grid.RowDefinitions>
    <RowDefinition Height="auto" />
    <RowDefinition Height="*" />
</Grid.RowDefinitions>

<Button Content="Do a foo!" Command="{Binding my:MyCustomControl.FooCommand}" />

<my:MyCustomControl Grid.Row="1">
    <!-- ... -->

    <!-- ... -->
</my:MyCustomControl>
</Grid>

<!-- ... -->
</Window>

问题出在 MyCustomControl 的“OnFoo”方法中。此方法是静态的,我需要访问 MyCustomControl 的方法“Foo()”。

关于如何做到这一点的任何建议?

【问题讨论】:

    标签: c# wpf mvvm custom-controls routed-commands


    【解决方案1】:

    您不能将sender 输入参数强制转换为您的类的实例吗?

    private static void OnFoo(object sender, RoutedEventArgs e)
    {
        ((MyCustomControl)sender).Foo();
    }
    

    【讨论】:

    • 那是我最初的想法,但它不起作用,因为我的发件人是按钮 (System.Windows.Controls.Button)。如果我在构造函数中将 typeof 更改为 MyCustomControl,它会禁用我的按钮。
    • 然后查看RoutedEventArgs 对象的内部...MyCustomControl 可能在e.OriginalSource 属性中。
    • @juFo 我遇到了和你一样的问题,想知道你是否有解决方案?自问题发布以来已经有一段时间了,但这里是希望:)
    • 我重新设计了应用程序,所以我不再需要它了。那是我的快速解决方案:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多