WPF中中触发器设置Button.Content

浏览:1092 发布日期:2023-02-13 17:09:18

有时我们根据状态,需要动态调整Button.Content的值,我们可能会这么设置:

<Style x:Key="enableButtonStyle2" TargetType="{x:Type Button}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=processList, Path=SelectedItem}" Value="{x:Null}">
                <Setter Property="IsEnabled" Value="False" />
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=processList, Path=SelectedItem.Status}" Value="0">
                <Setter Property="Content" Value="禁用" />
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=processList, Path=SelectedItem.Status}" Value="1">
                <Setter Property="Content" Value="启用" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

我们发现,无法成功,从msdn找到一个答案,地址为https://social.msdn.microsoft.com/Forums/security/zh-CN/ecdd95c9-7c58-4cf2-b53a-beeb65c31c62/1998133021299923530221457221203577432622content236462461565311?forum=wpfzhchs

我们可以通过设置内容模板来设置:

<Style x:Key="enableButtonStyle" TargetType="{x:Type Button}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=processList, Path=SelectedItem}" Value="{x:Null}">
                <Setter Property="IsEnabled" Value="False" />
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=processList, Path=SelectedItem.Status}" Value="0">
                <Setter Property="ContentTemplate">
                    <Setter.Value>
                        <DataTemplate DataType="Button">
                            <ContentPresenter Content="禁用" />
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=processList, Path=SelectedItem.Status}" Value="1">
                <Setter Property="ContentTemplate">
                    <Setter.Value>
                        <DataTemplate DataType="Button">
                            <ContentPresenter Content="启用" />
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </DataTrigger>
        </Style.Triggers>
    </Style>