Reputation: 455
I am trying to set the Foreground
property for a TextBox
specified in a DataTemplate
but the call doesn't work.
I have a UserControl
with the following XAML:
<UserControl x:Class="TextBoxColourTest.TextFrameControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
xmlns:clrtest="clr-namespace:TextBoxColourTest"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<DataTemplate x:Key="EditModeTemplate">
<TextBox Text="Hello"></TextBox>
</DataTemplate>
<Style TargetType="{x:Type clrtest:TextFrameControl}">
<Setter Property="ContentTemplate" Value="{StaticResource EditModeTemplate}"></Setter>
</Style>
</UserControl.Resources>
</UserControl>
Then I have some XAML that makes use of the TextFrameControl:
<Window x:Class="TextBoxColourTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:textBoxColourTest="clr-namespace:TextBoxColourTest"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<textBoxColourTest:TextFrameControl x:Name="TextFrameControl"></textBoxColourTest:TextFrameControl>
<Button Content="Red" Click="OnMouseUpRed"></Button>
<Button Content="Green" Click="OnMouseUpGreen"></Button>
</StackPanel>
</Grid>
</Window>
Then finally the code behind where I have event handlers for the buttons to change the foreground color:
namespace TextBoxColourTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnMouseUpRed(object sender, RoutedEventArgs routedEventArgs)
{
TextFrameControl.Foreground = new SolidColorBrush(Colors.Red);
}
private void OnMouseUpGreen(object sender, RoutedEventArgs routedEventArgs)
{
TextFrameControl.Foreground = new SolidColorBrush(Colors.Green);
}
}
}
When one of the color buttons is clicked then the foreground color does not change.
If I change the code so that I can alter the value of the font family or font size properties then that does work. Also, I've found that if I replace the TextBox
with a TextBlock
then the color does change.
Upvotes: 3
Views: 1589
Reputation: 128098
Bind the Foreground
property of the TextBox to that of the UserControl:
<DataTemplate x:Key="EditModeTemplate">
<TextBox Text="Hello"
Foreground="{Binding Foreground,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</DataTemplate>
Upvotes: 5