我正在尝试为Foreground
中指定的TextBox
设置DataTemplate
属性,但通话无效。
我有一个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>
然后我有一些使用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
,那么颜色确实会发生变化。
答案 0 :(得分:4)
将TextBox的Foreground
属性绑定到UserControl的属性:
<DataTemplate x:Key="EditModeTemplate">
<TextBox Text="Hello"
Foreground="{Binding Foreground,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</DataTemplate>