我有这个标记
<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}"/>
我的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
}
如果在DataGrid中选择了某个项目,CanExecute
上的RelayCommand
方法将返回true。
但是窗口打开时没有选择任何项目,导致按钮被禁用。如果我在DataGrid上选择了什么,就不会发生任何事情。
如果在DataGrid
?
答案 0 :(得分:6)
您可以为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>
答案 1 :(得分:1)
对我来说,这样可以通过在选择发生时对命令执行RaiseCanExecuteChanged()方法来完成。有很多方法可以实现这一点(直接事件调用,IsSelected绑定到您的视图模型中引发事件,附加行为等),您最好调查所有这些并确定哪种方法最适合您的方案。
答案 2 :(得分:1)
我将事件更改为
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
现在它正在发挥作用。