2012-10-03 72 views
0

我遇到了xaml问题...我创建的按钮未启用。这里是XAML部分:xaml中的禁用按钮

<Button Margin="0,2,2,2" Width="70" Content="Line" 
     Command="{x:Static local:DrawingCanvas.DrawShape}" 
     CommandTarget="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
      AncestorType={x:Type Window}}, Path=DrawingTarget}" 
     CommandParameter="Line">   
</Button> 

构造函数之前有云:

public static RoutedCommand DrawShape = new RoutedCommand(); 

在构造函数,我有:

this.CommandBindings.Add(new CommandBinding(DrawingCanvas.DrawShape, DrawShape_Executed, DrawShapeCanExecute)); 

然后,我有:

private void DrawShapeCanExecute(object sender, CanExecuteRoutedEventArgs e) 
{ 
    e.CanExecute = true; **//Isn't this enough to make it enable?** 
    en.Handled = true; 

}

private void DrawShape_Executed(object sender, ExecutedRoutedEventArgs e) 
{ 
    switch (e.Parameter.ToString()) 
    { 
     case "Line": 
      //some code here (incomplete yet) 
      break; 
    } 

当我删除块中的第一行(Command="{x:Static ...}")时,它会再次启用!

+0

所以'Command'你绑定必须返回'CanExecute = FALSE'。你可以发布显示'DrawingCanvas.DrawShape'的代码部分吗? – McGarnagle

+0

如何定义'DrawingCanvas.DrawShape'? –

+0

** DrawingCanvas **是一个类,在这个类中** DrawShape **被定义为'public static RoutedCommand DrawShape = new RoutedCommand();' –

回答

2

确保该命令的CanExecute属性返回true。如果它返回false,它会自动禁用使用该命令的控件。

可以执行应该返回一个布尔,我有点惊讶,不给编译错误。无论如何设法改变它。

private bool DrawShapeCanExecute(object sender, CanExecuteRoutedEventArgs e) 
{ 
    return true; 
} 

编辑:

好,因为你刚刚发现你想要的是一个简单的按钮,在这里执行命令是一个非常简单的实现,从我最近的项目之一复制。首先在某个地方定义这个类。

public class GenericCommand : ICommand 
{ 
    public event EventHandler CanExecuteChanged { add{} remove{} } 

    public Predicate<object> CanExecuteFunc{ get; set; } 

    public Action<object> ExecuteFunc{ get; set; } 

    public bool CanExecute(object parameter) 
    { 
     return CanExecuteFunc(parameter); 
    } 

    public void Execute(object parameter) 
    { 
     ExecuteFunc(parameter); 
    } 
} 

下一页在您的视图模型中定义的命令和定义这两个我在通用命令创建的特性(它只是与实现ICommand接口走来基本的东西)。

public GenericCommand MyCommand { get; set; } 

MyCommand = new GenericCommand(); 
MyCommand.CanExecuteFunc = obj => true; 
MyCommand.ExecuteFunc = obj => MyMethod; 

private void MyMethod(object parameter) 
{ 
     //define your command here 
} 

然后只需将按钮连接到您的命令。

<Button Command="{Binding MyCommand}" /> 

如果这对你来说太过分了(MVVM确实需要一些额外的初始设置)。你可以随时做到这一点...

<Button Click="MyMethod"/> 

private void MyMethod(object sender, RoutedEventArgs e) 
{ 
    //define your method 
} 
+0

CanExecute在其中有'e.CanExecute = true;',它是CommandBinding()的第三个参数...但它被禁用。 –

+0

@amitkohan从你发布的内容看来,代码永远不会被调用,但是如果没有发布更多关于如何设置的东西,很难说。你可以发布如何定义命令本身(DrawingCanvas.DrawShape) –

+0

这是我所有的1)'声明DrawShape'作为路由命令2)bindingcommand 3)设置'DrawShapeCanExecute()'4)最后处理程序是'DrawShape_Executed )'。我在这里错过吗? –