wpf 如何仅在 DataGrid 中选择一行时启用按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19481291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:54:30  来源:igfitidea点击:

How to enable a button only if a row is selected in DataGrid?

c#wpfdatagridicommand

提问by BrunoLM

I have this markup

我有这个标记

<DataGrid Margin="10,10,10,48" AutoGenerateColumns="False" Name="grdUsers"
          ItemsSource="{Binding Users}"
>
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}" />
        <DataGridTextColumn Header="Username" Width="*" Binding="{Binding Username}" />
        <DataGridTextColumn Header="Password" Width="*" Binding="{Binding Password}" />
        <DataGridTextColumn Header="Role" Width="*" Binding="{Binding Path=Role.Name}" />
    </DataGrid.Columns>
</DataGrid>
<Button Content="Add" HorizontalAlignment="Left" Margin="10,0,0,10" Width="75" Height="20" VerticalAlignment="Bottom"/>
<Button Content="Edit" HorizontalAlignment="Left" Margin="90,0,0,10" Width="75" Height="20" VerticalAlignment="Bottom"/>

<Button Content="Remove" Margin="0,0,10,10" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="75"
        Command="{Binding Remove}" CommandParameter="{Binding ElementName=grdUsers, Path=SelectedItem}"/>

My RelayCommand

我的中继命令

public class RelayCommand : ICommand
{
    private readonly Action<object> execute = null;
    private readonly Predicate<object> canExecute = null;

    public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
    {
        this.execute = execute;
        this.canExecute = canExecute;
    }


    #region ICommand members

    public bool CanExecute(object parameter)
    {
        return canExecute == null ? true : canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged;

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

    #endregion
}

My CanExecutemethod on my RelayCommandreturns true if there is a item selected in the DataGrid.

如果在 DataGrid 中选择了一个项目,我的CanExecute方法RelayCommand将返回 true。

But the Window opens without any items selected, causing the button to be disabled. If I select something on the DataGrid nothing happens.

但是窗口打开时没有选择任何项目,导致按钮被禁用。如果我在 DataGrid 上选择某些内容,则不会发生任何事情。

How can I "refresh" the button if a row has been selected in the DataGrid?

如果在DataGrid? 中选择了一行,我如何“刷新”按钮?

采纳答案by BrunoLM

I changed the event to

我将事件更改为

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

And now it is working.

现在它正在工作。

回答by kmatyaszek

You can create style for Buttonand using DataTrigger:

您可以创建样式Button并使用DataTrigger

<Button Content="Remove" Margin="0,0,10,10" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="75"
    Command="{Binding Remove}" CommandParameter="{Binding ElementName=grdUsers, Path=SelectedItem}">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="IsEnabled" Value="True" />
            <Setter Property="Opacity" Value="1" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=grdUsers, Path=SelectedItem}" Value="{x:Null}">
                    <Setter Property="IsEnabled" Value="False" />
                    <Setter Property="Opacity" Value=".5" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

回答by Firoso

Seems to me like this could be accomplished by executing the RaiseCanExecuteChanged() method on the command when the selection occurs. There are a number of ways to accomplish this (direct event invocation, IsSelected bindings into your view model that raise the event, Attached Behaviors, etc.) and you would do well to investigate all of them and decide which works best for your scenario.

在我看来,这可以通过在选择发生时对命令执行 RaiseCanExecuteChanged() 方法来完成。有多种方法可以完成此操作(直接事件调用、将 IsSelected 绑定到引发事件的视图模型中、附加行为等),您最好调查所有这些方法并确定哪种方法最适合您的场景。