I have a TextBlock that is inside a Control Template. I want to change the Text for said TextBlock with the Text value of a TextBox. The value is meant to be set within a button click event however, with the way I've tried to do this it doesn't work. The click event will give out an error stating that text
is null.
I am new to WPF and would appreciate any help.
XAML for Control Template:
<Window.Resources>
<ControlTemplate x:Key="panel" TargetType="Button">
<Grid>
<Rectangle x:Name="rectangle" Width="auto" Height="55" RadiusX="10" RadiusY="10"
Fill="White">
</Rectangle>
<TextBlock x:Name="txtBlk" Text="" Margin="10,10,0,0" />
</Grid>
</ControlTemplate>
</Window.Resources>
C# for Button_Click event
private void panelBtn_Click(object sender, RoutedEventArgs e)
{
var text = (TextBlock)this.Template.FindName("txtBlk", this);
text.Text = txtBox.Text;
}
CodePudding user response:
You should reference the template of the button like this..
private void panelBtn_Click(object sender, RoutedEventArgs e)
{
if (sender is Button btn)
{
var text = btn.Template.FindName("txtBlk", btn) as TextBlock;
text.Text = txtBox.Text;
}
}
CodePudding user response:
@MuhammadSulaiman answered you correctly, but I would suggest that you change the implementation.
Rather than looking for an element in a template, it's better to add a resource to which this element will refer and change this resource.
<Window.Resources>
<sys:String x:Key="button.Text">Some Text</sys:String>
<ControlTemplate x:Key="panel" TargetType="Button">
<Grid>
<Rectangle x:Name="rectangle" Width="auto" Height="55" RadiusX="10" RadiusY="10"
Fill="White">
</Rectangle>
<TextBlock x:Name="txtBlk"
Text="{DynamicResource button.Text}"
Margin="10,10,0,0" />
</Grid>
</ControlTemplate>
</Window.Resources>
private void panelBtn_Click(object sender, RoutedEventArgs e)
{
if (sender is FrameworkElement elm)
{
elm.Resources["button.Text"] = txtBox.Text;
}
}
You can also change the initial text in XAML:
<Button Template="{DynamicResource panel}">
<Buttun.Resources>
<sys:String x:Key="button.Text">Other Text</sys:String>
</Buttun.Resources>
</Buttun>
In the same way, you can set a common initial text for all buttons located in one common container, through the resources of this container.