【问题标题】:按钮命令在第一次单击时不会触发
【发布时间】:2014-01-17 05:13:42
【问题描述】:

在我的 WPF 应用程序中,我在绑定到 RelayCommand 的数据网格的每一行中都有一个按钮。如果有人连续点击按钮,则执行该命令的底层方法。

不幸的是,这仅在第二次点击时有效!第一次单击该行中的按钮时,仅选择了该行。在第二次单击时执行命令。

如果我选择了之前的行,那么它会在第一次单击按钮时起作用。

我做错了什么?

XAML:

<DataGrid AutoGenerateColumns="False" 
          IsReadOnly="True" 
          Style="{StaticResource DataGridStyle}"
          ItemsSource="{Binding Path=Rows, Mode=OneWay}" 
          SelectedItem="{Binding Path=SelectedRow}">

<DataGrid.Columns>
    <DataGridTextColumn Header="Number" 
                        Width="Auto"
                        Binding="{Binding Path=Number}" />
    <DataGridTemplateColumn Header= "Cancel"
                            Width="Auto"  >
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button Command="{Binding RelativeSource={RelativeSource 
                                                          AncestorType=Expander}, 
                                          Path=DataContext.CancelCommand}" 
                        HorizontalAlignment="Center" 
                        Width="20" 
                        IsEnabled="{Binding IsCancelable}"
                        Visibility="{Binding RelativeSource={RelativeSource 
                                             AncestorType=DataGrid}, 
                                             Path=DataContext.PermissionToWrite, 
                                             Converter={StaticResource 
                                                      boolToVisibilityConverter}}"
                         >X</Button>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>

【问题讨论】:

标签: wpf xaml binding wpfdatagrid


【解决方案1】:

我目前面临同样的问题。我发现如果我先单击 Datagrid 上的某个位置,那么该按钮将起作用。但是,如果您使用Datagrid.SelectAll()Datagrid.SelectedItem = ... 以编程方式选择行,那么它仍然不起作用。我发现的解决方法是在将鼠标悬停在行上时将该行设置为正在编辑。您可以使用以下样式执行此操作:

    <Page.Resources>
        <Style TargetType="DataGridCell">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="IsEditing" Value="True" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Page.Resources>

即使您已明确将列设置为不可编辑,这似乎也有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多