You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WPF中如何仅禁用DataGrid单个单元格内的按钮?

解决DataGrid中仅禁用指定单元格按钮而非整行的问题

你当前的代码是给DataGridCell设置禁用触发器,单元格内的按钮会继承单元格的IsEnabled状态,导致对应单元格整体被禁用,而非仅按钮本身。

解决方案1:直接绑定按钮的IsEnabled属性

将按钮的IsEnabled直接绑定到数据模型的Enabled属性,最简单直接:

<DataGridTemplateColumn Header="Azione" Width="3*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Click="btnEffettuaOperazioni_Click"
                    IsEnabled="{Binding Enabled}">
                <TextBlock Text="Effettua operazioni"/>
            </Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

解决方案2:给按钮添加样式触发器(适合复杂逻辑)

如果需要更复杂的触发条件,可给按钮单独设置样式触发器:

<DataGridTemplateColumn Header="Azione" Width="3*">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Click="btnEffettuaOperazioni_Click">
                <TextBlock Text="Effettua operazioni"/>
                <Button.Style>
                    <Style TargetType="Button">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Enabled}" Value="false">
                                <Setter Property="IsEnabled" Value="False"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Button.Style>
            </Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

注意事项

移除之前设置的DataGrid.CellStyle,避免单元格的状态影响按钮。将禁用逻辑直接作用在按钮上,就能精准控制单个按钮的启用状态,而不会波及整个单元格或行。

内容的提问来源于stack exchange,提问作者freedmaaan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 20:35:20