WPF中禁用按钮

时间:2012-10-03 22:01:39

标签: c# xaml wpf-controls

我正在尝试做一些非常简单和基本的事情。如果我错了,请纠正我:

考虑一个简单的按钮,然后考虑与之关联的方法。但是,如果我在DrawShapeCanExecute()上更改返回类型,我将获得none(禁用按钮),然后我会收到一条错误消息:

bool WpfApplication8.DrawingCanvas.DrawShapeCanExecute(object,System.Windows.Input.CanExecuteRoutedEventArgs)'返回类型错误

public static RoutedCommand DrawShape = new RoutedCommand();


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



private void DrawShape_Executed(object sender, ExecutedRoutedEventArgs e)
{

}

其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>

3 个答案:

答案 0 :(得分:2)

您需要将事件标记为已处理:

e.CanExecute = true;
e.Handled = true;

答案 1 :(得分:0)

http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx我发现你需要绑定CanExecute和Executed处理程序。它会是这样的:

<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:DrawingCanvas.DrawShape }"
                Executed="DrawShape_Executed"
                CanExecute="DrawShapeCanExecute" />
</Window.CommandBindings>

<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>

答案 2 :(得分:0)

在MainWindow.xaml.cs中添加此语句解决了这个问题:

public IInputElement DrawingTarget { get { return _canvas; } }

关键是我们正在添加一个不在形式上但在画布上的菜单栏。