如何在.xaml中从.cs绑定样式的命令?

时间:2014-01-03 07:38:41

标签: c# wpf button command

现在,我正在嘲笑MessageBox。我在.xaml中的Style.Template中构建Close Button,但我不知道如何使用CloseCommand绑定命令。是否能用系统关闭命令进行混搭?

.cs(定义自定义控件):

internal sealed class MessageBoxModule : Window
{
    #region Constructor
    static MessageBoxModule()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof(MessageBoxModule),
            new FrameworkPropertyMetadata(typeof(MessageBoxModule)));
    }

    public MessageBoxModule()
    {
        WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
        AllowsTransparency = true;
        WindowStyle = System.Windows.WindowStyle.None;
        ShowInTaskbar = false;

        try
        {
            Resources.Source = new Uri(@"/Wpf.Controls;component/Themes/Generic.xaml", UriKind.Relative);
        }
        catch
        { }
...

.xaml(是一个ResourceDictionary文件,为MessageBoxModule提供样式):

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Wpf.Controls">
        <Style TargetType="{x:Type local:MessageBoxModule}">
            <Setter Property="Template" >
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:MessageBoxModule}">
                        <Border ...>
                            <Button x:Name="CloseButton".../>
                            ...
                        </Border>
...

查看红色按钮,我不知道如何为它绑定命令:

enter image description here

这是整个解决方案:

的.cs:

internal sealed class MessageBoxModule : Window
{
    public MessageBoxModule()
    {
        InputGestureCollection inputGestures = new InputGestureCollection();
        inputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));
        CloseCommand = new RoutedCommand(
            "CloseCommand",
            typeof(MessageBoxModule),
            inputGestures);
        CommandBindings.Add(new CommandBinding(CloseCommand, CloseCommandExecuted));
    }

    public static readonly DependencyProperty CloseCommandProperty =
        DependencyProperty.Register(
            "CloseCommand", 
            typeof(RoutedCommand), 
            typeof(MessageBoxModule));

    public RoutedCommand CloseCommand
    {
        get { return (RoutedCommand)GetValue(CloseCommandProperty); }
        set { SetValue(CloseCommandProperty, value); }
    }

    public void CloseCommandExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        Close();
    }
}

的.xaml:

<ResourceDictionary >
    <Style TargetType="{x:Type local:MessageBoxModule}">
        <Setter Property="Template" >
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:MessageBoxModule}">
                    <Border ...>
                        <Button x:Name="CloseButton" Command="{TemplateBinding CloseCommand}"/>
...

2 个答案:

答案 0 :(得分:0)

@SubmarineX

为按钮创建一个DataContext,例如

public class ButtonViewModel{

private RelayCommand _CloseCommand;

public ICommand CloseCommand
        {
            get { return _CloseCommand?? (_CloseCommand= new RelayCommand(p => Close())); }
        }

void Close(){

//Here u cn write the  logic which close the window from this view model or  raise an event which handled by your button container

}
}


    public class RelayCommand : ICommand
    {
        #region Fields

        private readonly Action<object> _execute;
        private readonly Predicate<object> _canExecute;

        #endregion // Fields

        #region Constructors

        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }

        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null) throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }

        #endregion // Constructors

        #region ICommand Members [DebuggerStepThrough]

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

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

        #endregion // ICommand Members }
    }

in xaml

<Button x:Name="CloseButton" Command="{Binding Close}"/>

确保DataContext可用于按钮

答案 1 :(得分:0)

从类dependency property公开ICommandMessageBoxModule

public ICommand CloseCommand
{
   get { return (ICommand)GetValue(CloseCommandProperty); }
   set { SetValue(CloseCommandProperty, value); }
}

public static readonly DependencyProperty CloseCommandProperty =
   DependencyProperty.Register("CloseCommand", typeof(ICommand), 
                                typeof(MessageBoxModule));

使用TemplateBinding绑定到Command,如下所示:

<Button x:Name="CloseButton" Command="{TemplateBinding CloseCommand}"/>

由于命令已公开,您可以从外部绑定它:

<local:MessageBoxModule CloseCommand="{Binding ViewModelCommand}"/>

假设您已经安装了View模型并且它已经包含要将其绑定到关闭按钮的ICommand。