4

我有这个标记

<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}"/>

我的中继命令

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
}

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

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

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

4

3 回答 3

8

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>
于 2013-10-20T18:45:18.870 回答
1

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

于 2013-10-20T18:44:30.047 回答
1

我将事件更改为

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

现在它正在工作。

于 2013-11-22T17:30:13.627 回答