【发布时间】: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