简体   繁体   中英

C# UWP TextBlock text change in Button Style programatically

I have a button with Resource style. I would like to change Text of TextBlock in Button Content. I didn't find any solution.

Any idea?

<Style x:Key="NavigationLogoutButtonStyle" TargetType="Button" BasedOn="{StaticResource NavigationBackButtonNormalStyle}">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Height" Value="48"/>
<Setter Property="Width" Value="NaN"/>
<Setter Property="MinWidth" Value="48"/>
<Setter Property="AutomationProperties.Name" Value="Logout"/>
<Setter Property="Content">
    <Setter.Value>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="48" />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <FontIcon Grid.Column="0" FontSize="16" Glyph="&#xE1E0;" VerticalAlignment="Center" HorizontalAlignment="Center"/>
            <StackPanel Grid.Column="1" Orientation="Vertical">
                <TextBlock Style="{ThemeResource BodyTextBlockStyle}" Text="!!!TEXT HERE PROGRAMATICALLY!!!" Foreground="{StaticResource MainColorBrush}" FontSize="13" VerticalAlignment="Center" />
                <TextBlock Style="{ThemeResource BodyTextBlockStyle}" Text="{StaticResource LogoutButtonText}" VerticalAlignment="Center" />
            </StackPanel>
        </Grid>
    </Setter.Value>
</Setter>

You can do a hack, change the line:

<TextBlock Style="{ThemeResource BodyTextBlockStyle}" Text="!!!TEXT HERE PROGRAMATICALLY!!!" Foreground="{StaticResource MainColorBrush}" FontSize="13" VerticalAlignment="Center" />

to

<TextBlock Style="{ThemeResource BodyTextBlockStyle}" Text="{Binding Tag}" Foreground="{StaticResource MainColorBrush}" FontSize="13" VerticalAlignment="Center" />

And set the Tag property of your Button in code.

The proper way to do it would be declare new DependencyProperty type string of a CustomButton which inherits from Button. Then apply the Style to the new CustomButton type. Bind the Text property to the newly created DependencyProperty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM