amit kohan
amit kohan

Reputation: 1618

Disabled button in WPF

I'm trying to do something very simple and basic. Correct me if I'm wrong:

Think of a simple button and then methods associated to it as following. However, I'm getting either none (a disabled button) of if I change returning type on DrawShapeCanExecute() then I would get an error message as:

bool WpfApplication8.DrawingCanvas.DrawShapeCanExecute(object, System.Windows.Input.CanExecuteRoutedEventArgs)' has the wrong return type

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

}

its xaml portion has:

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

Upvotes: 0

Views: 193

Answers (3)

amit kohan
amit kohan

Reputation: 1618

Adding this statement in MainWindow.xaml.cs solves it:

public IInputElement DrawingTarget { get { return _canvas; } }

The point is that we are adding a menubar not on form but on a canvas.

Upvotes: 0

Edgar Hernandez
Edgar Hernandez

Reputation: 4030

From http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx I see you need to bind the CanExecute and Executed handlers. It would be something like:

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

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292425

You need to mark the event as handled:

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

Upvotes: 2

Related Questions