2011年6月14日 星期二

在WPF應用程式自訂Command

1.在WPF應用程式中加入一個類別
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace WpfApplication1 {
public class UICommands {
        public static RoutedUICommand ChangeBGColorCommand =
            new RoutedUICommand ( );
    }
}
2.在XAML Window 中加入命名空間
xmlns:cmd="clr-namespace:WpfApplication1"
image
3.加Window.CommandBindings
<Window.CommandBindings>
       <CommandBinding x:Name="changebg"  Executed="changebg_Executed"
                        Command="cmd:UICommands.ChangeBGColorCommand"
                       />
   </Window.CommandBindings>
image
4.寫changebg_Executed 事件
private void changebg_Executed ( object sender , ExecutedRoutedEventArgs e ) {
           this.button1.Background = new SolidColorBrush ( Colors.Red );
       }
image
5.在Window加入StackPanel 、Menu、MenuItem 、Button
<StackPanel >
        <Menu>
            <MenuItem Header="_Menu" >
                <MenuItem Header="Change "  
                          Command="cmd:UICommands.ChangeBGColorCommand"
                 />
             
            </MenuItem>
        </Menu>
        <Button Content="Button" Height="23" Name="button1" Width="75" />
    </StackPanel>
image
6.Run
image

沒有留言:

總網頁瀏覽量