2013-10-20 43 views
2

我有這個標記如何僅在DataGrid中選擇一行時啓用按鈕?

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

CanExecuteRelayCommand返回true方法如果在DataGrid中選擇一個項目。

但是,窗口打開時未選擇任何項目,導致按鈕被禁用。如果我在DataGrid上選擇一些東西,則不會發生任何事

如何在DataGrid中選擇一行時「刷新」按鈕?

+0

您正在使用哪個'RelayCommand'版本? –

回答

1

我改變了事件

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

現在它正在發揮作用。

1

對我來說這似乎可以通過在選擇發生時在命令上執行RaiseCanExecuteChanged()方法來完成。有很多方法可以實現這一點(直接事件調用,IsSelected綁定到您的視圖模型中以引發事件,附加行爲等),您將很好地調查所有這些方法並決定哪種方法最適合您的方案。

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> 
相關問題