按钮已禁用但未显示为灰色

时间:2014-03-02 12:32:09

标签: c# wpf xaml mvvm

我有一个按钮,它被命令将状态从启用更改为禁用。 当按钮被禁用时我无法点击它(没有响应...)但是 它的颜色和以前一样保持不变(比如启用模式),我该怎么办呢 当按钮被禁用时,它会变成灰色的颜色。

   <Button Command="{Binding Select}"
                        CommandParameter="{Binding ElementName=SelWindow}"
                        Width="125"
                        Height="26"
                        Background="#f0ab00"
                        Content="Run"
                        IsEnabled="{Binding SelectServEnabled}"

                        FontSize="16"
                        Foreground="#ffffff"
                        Margin="0,0,80,10" />

1 个答案:

答案 0 :(得分:0)

首先;确保正确定义了SelectServEnabled。

其次;命令包含CanExecute方法,用于更改按钮的启用/禁用状态。不要使用IsEnabled,而是在命令的CanExecute方法中处理它。

第三;正如FlatEric所说,样式覆盖的可能性很高(检查你的主题文件夹或Generic.xaml或类似的东西,并检查TargetType Button的任何样式

我已经像这样测试了你的代码并且工作正常:

    public ICommand Select
    {
        get { return (ICommand)GetValue(SelectProperty); }
        set { SetValue(SelectProperty, value); }
    }
    public static readonly DependencyProperty SelectProperty =
        DependencyProperty.Register("Select", typeof(ICommand), typeof(MainWindow), new UIPropertyMetadata(null));

    public bool SelectServEnabled
    {
        get { return (bool)GetValue(SelectServEnabledProperty); }
        set { SetValue(SelectServEnabledProperty, value); }
    }
    public static readonly DependencyProperty SelectServEnabledProperty =
        DependencyProperty.Register("SelectServEnabled", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(true));

这是一个简单的命令:

public class MyCommand : ICommand
{
    public bool CanExecute(object parameter)
    {
        //here you can change the enabled/disabled state of 
        //any button that bind to this command

        return true;        
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
    }
}