I changed my UWP application to have a responsive UI. Since then I have a problem to put text in a button. Here's the XAML:
<Page
x:Class="Stock_Manager_Windows.IncomeOrder3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Stock_Manager_Windows"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="#FFBBBBBB">
<Grid.RowDefinitions>
...
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
...
</Grid.ColumnDefinitions>
...
<Button x:Name="Envoyer" Content="Envoyer" HorizontalAlignment="Stretch" Margin="2,2,0,2" VerticalAlignment="Stretch" Grid.Column="4" Grid.ColumnSpan="2" Grid.Row="4" Background="#249C23" Foreground="White" FontWeight="Bold" Click="buttonSendSelectedItems_Click">
<Button.ContentTemplate>
<DataTemplate x:Name="EnvoyerDataTemplate" >
<Viewbox>
<TextBlock x:Name="EnvoyerTxt" Text="Envoyer"/>
</Viewbox>
</DataTemplate>
</Button.ContentTemplate>
</Button>
...
</Grid>
</Page>
Before the modif I used to update the text in the button with this C# code :
Envoyer.Content = "Envoyer (" + count + ")";
Now its not possible... Then at first I tried with :
envoyerTxt.Text = "Envoyer (" + count + ")";
I tried to use the solutions explained with the following links, but it seems the code is obsolete, not related or I'm too stupid to understand it.
WPF How to access control from DataTemplate
Accessing a control which is in a contentpresenter in c#
How do I access a control inside a XAML DataTemplate?
how to access a control within Data Template from code behind?
FindVisualChild reference issue
Is someone could explain me the solution ? Maybe the problem is not in c# code but in the XAML, I have no clues.
Inside your ContentTemplate
change the TextBlock
to this.
<TextBlock x:Name="EnvoyerTxt" Text="{Binding}" />
Which means now, whatever content (Text) is set it will be bind to your template TextBlock
text property and it will change accordingly.
To make it also clear, You can not access an element by it's name inside a template. Because templates are loaded at runtime and not at compile time. That's why inside templates only binding will work for assigning data.