简体   繁体   中英

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.

Ie 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}" />

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.

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");
   }
}

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