1

XAML:

<Window x:Class="WorkOut.ToggleButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:WorkOut.Code"        
Title="ToggleButton" Height="300" Width="300">
<Grid>
    <StackPanel Orientation="Vertical">
        <ToolBar Height="40" VerticalAlignment="Top">
            <Button Margin="0,3,0,3" Padding="2" HorizontalContentAlignment="Left"
                    Command="{x:Static s:MyCanvas.AddNewTab}"
                    CommandTarget="{Binding ElementName=MyCanvas}">
                <Button.Content>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>
                        <TextBlock Margin="3" Text="Append New Tab" VerticalAlignment="Center" Grid.Column="1"/>
                    </Grid>
                </Button.Content>
            </Button>
        </ToolBar>
        <Grid x:Name="MyGrid">
        </Grid>               
    </StackPanel>
</Grid>

代码:

public ToggleButton()
    {
        InitializeComponent();

        MyCanvas MyCanvas1 = new MyCanvas();
        MyCanvas1.Name = "MyCanvas";
        MyCanvas1.Background = System.Windows.Media.Brushes.LightBlue;
        MyCanvas1.Height = 100;
        MyCanvas1.Width = 100;
        MyCanvas1.HorizontalAlignment = HorizontalAlignment.Left;
        MyGrid.Children.Add(MyCanvas1);

        MyCanvas MyCanvas2 = new MyCanvas();
        MyCanvas2.Name = "MyCanvas";
        MyCanvas2.Background = System.Windows.Media.Brushes.Beige;
        MyCanvas2.Height = 100;
        MyCanvas2.Width = 100;
        MyCanvas2.HorizontalAlignment = HorizontalAlignment.Right;
        MyGrid.Children.Add(MyCanvas2);
    }
class MyCanvas : Canvas
{
    public static RoutedCommand AddNewTab = new RoutedCommand();
    public MyCanvas()
    {
        this.CommandBindings.Add(new CommandBinding(MyCanvas.AddNewTab, AddNewTab_Executed, AddNewTab_Enabled));
    }
    private void AddNewTab_Executed(object sender, ExecutedRoutedEventArgs e)
    {
         MessageBox.Show (this.Background.ToString());
    }
    private void AddNewTab_Enabled(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }
}       

上面的代码在网格控件上创建了两个画布,并且禁用了工具栏中的 addnew 按钮,尽管它已绑定到 MyCanvas 元素。

可能是我采用了错误的方法...

任何帮助,非常感谢。

谢谢KJ

4

2 回答 2

2

可能是因为您的命令返回 CanExecute() 错误,因为它没有命令目标。

于 2009-02-28T18:53:54.757 回答
0

您是否尝试过设置事件已处理的 CanExecute 处理程序?

private void AddNewTab_Enabled(object sender, CanExecuteRoutedEventArgs e)    
{        
    e.CanExecute = true;    
    e.Handled = true
}
于 2009-03-20T16:59:59.307 回答