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

3

我正在尝试为在DataTemplate中指定的TextBox设置Foreground属性,但是调用无效。

我有一个带有以下XAML的UserControl

<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>

然后我有一些使用TextFrameControl的XAML:

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

当单击其中一个颜色按钮时,前景色不会改变。
如果我更改代码以便可以更改字体系列或字体大小属性的值,则可以运行。此外,我发现如果我将 TextBox 替换为 TextBlock ,则颜色会更改。
1个回答

5

将TextBox的Foreground属性绑定到UserControl的属性上:

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

1
那个可行了,但是它是怎么做到的呢?任何指针都将不胜感激。我不明白为什么如果我用TextBlock替换TextBox,我就可以更改字体系列和大小,或者更改前景颜色。 - randusr836
不知道为什么 TextBlock 继承了前景值,而 TextBox 没有。 - Clemens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接