簡體   English   中英

WPF RoutedCommand和CustomControl實現

[英]WPF RoutedCommand and CustomControl implementation

我有一個窗口,其中有一個按鈕和一個CustomControl。 當我單擊按鈕時,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()”。

有關如何執行此操作的任何建議?

您是否可以將sender輸入參數轉換為類的實例?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM