无法在 WPF 的 DataTemplate 中为 TextBox 设置前景

Cannot Set Foreground For TextBox in DataTemplate in WPF

我正在尝试为 DataTemplate 中指定的 TextBox 设置 Foreground 属性,但调用不起作用。

我有一个 UserControl 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>

然后我有一些 XAML 使用了 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>

最后是我有按钮事件处理程序以更改前景色的代码:

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

单击其中一个颜色按钮时,前景色不会改变。

如果我更改代码以便可以更改字体系列或字体大小属性的值,那么它就可以工作。另外,我发现如果我用 TextBlock 替换 TextBox 那么颜色确实会改变。

将 TextBox 的 Foreground 属性 绑定到 UserControl:

<DataTemplate x:Key="EditModeTemplate">
    <TextBox Text="Hello"
        Foreground="{Binding Foreground,
                     RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</DataTemplate>