Ksice
Ksice

Reputation: 3327

How to change XAML elemen't template from code-behind?

I have next button's style defined in resources:

<Style x:Key="OKBtn" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
                    <Rectangle .../>

                    <TextBlock x:Name="Text" ..>
                        <Run Language="en-en" Text="OK"/>
                    </TextBlock>                        
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And I want in some specified case from code change Button's text.

I.e. change "OK" (<Run Language="en-en" Text="OK"/>) to "Accept". How can I do that?

Is it possible to access this TextBlock "Text" and change content exactly for my one button, but not for all OK buttons?

My button:

<Button x:Name="OkButton" Style="{DynamicResource OKBtn}" />

Upvotes: 4

Views: 1663

Answers (2)

bars222
bars222

Reputation: 1660

You can borrow some props from template Template, for example Tag property. So the TextBlock text in the ControlTemplate should be like this.

<Run Language="en-en" Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Tag}"/>

And you can change the button caption by setting it's Tag property.

OkButton.Tag = "Accept";

And for not set all button texts manually you can create some ValueConverter to set TextBlock text in the ControlTemplate to the "Ok" whenever Tag property is empty.

Upvotes: 3

StepUp
StepUp

Reputation: 38094

At first, you should declare ContentPresenter to show any object in your Content property of Button control.

<Style x:Key="OkBtn" TargetType="Button">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Rectangle/>
                    <ContentPresenter Content="{Binding Path=Content, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}"></ContentPresenter>
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

Then, it is possible to set another Content by using code behind or binding:

By code behind:

okButton.Content="desirableText";

By binding:

<Button x:Name="OkButton" Style="{DynamicResource OKBtn}" Content="{Binding FooText}" />

private string fooText;

public string FooText
{
   get { return fooText; }
   set
   {
       fooText = value;
       OnPropertyChanged("FooText");
   }
}

Upvotes: 0

Related Questions