Changing Button's content to DataTemplate based on ViewModel property

24 Views Asked by At

I have a button that I want to change its content from simple text to a DataTemplate when a bool property I have in my ViewModel is set to true. For example, the button already has a style and looks like:

<Button
    Command="{Binding SomeCommand}"
    Content="Export"
    Style="{StaticResource NeutralButtonStyle}" />

Now, when a property in my viewmodel called IsExporting is set to True, I want to change the button's content from text to a specified DataTemplate called LoadingSpinner.

In a different control, I was able to achieve this in its ContentPresenter's Style triggers like this:

<DataTrigger Binding="{Binding IsExporting}" Value="True">
    <Setter Property="ContentTemplate" Value="{StaticResource LoadingSpinner}" />
</DataTrigger>

I've tried a few combinations of the above on the Button but cannot get the text to change to the DataTemplate.

The full style currently looks like:

<Style x:Key="NeutralButtonStyle" TargetType="Button">
    <Setter Property="Padding" Value="12,8" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid>
                    <Border
                        x:Name="BackgroundBorder"
                        Background="{TemplateBinding Background}"
                        CornerRadius="4">
                    </Border>
                    <ContentPresenter
                        x:Name="ContentPresenter"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center" />
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Background" Value="LightGray" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Update: I'm no longer setting the initial content (a string) on the button itself.

<Button Command="{Binding SomeCommand}" Style="{StaticResource NeutralButtonStyle}" />

I added these style triggers in the style above:

<Style.Triggers>
    <DataTrigger Binding="{Binding IsExporting}" Value="True">
        <Setter Property="Content" Value="{StaticResource LoadingSpinner}" />
    </DataTrigger>
    <DataTrigger Binding="{Binding IsExporting}" Value="False">
        <Setter Property="Content" Value="Export" />
    </DataTrigger>
</Style.Triggers>

The "False" datatrigger works. I see "Export" on the button. The DataTemplate LoadingSpinner does not though.

0

There are 0 best solutions below