【发布时间】:2012-09-23 08:21:58
【问题描述】:
我有一个 UserControl,它在 DataTemplate 中只包含一个 TextBlock 和 TextBox。这是通过以下方式完成的:
<UserControl.Resources>
<DataTemplate DataType="{x:Type Binding:StringBindingData}" x:Key="dataTemp">
<StackPanel Orientation="Horizontal" Name="sPanel">
<TextBlock Name="txtDescription" Text="{Binding Description}" />
<TextBox Name="textboxValue" Text="{Binding Mode=TwoWay, Path=Value, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid>
<ItemsControl Name="textItemsControl" ItemsSource="{Binding}"/>
</Grid>
我需要能够在不同的情况下对 TextBlock/TextBox 应用不同的样式。例如,在某些情况下,我希望能够将白色前景应用到 TextBlock 或更改 TextBox 的宽度。
我尝试了几种不同的方法: 在使用控件的窗口中,我设置了 TextBlock 的样式:
<Style TargetType="{x:Type TextBlock}" >
<Setter Property="Foreground" Value="White" />
</Style>
这适用于窗口中的所有其他文本块。
我还尝试使用
在代码隐藏中获取 DataTemplatevar myDataTemplate = (DataTemplate)this.Resources["dataTemp"];
但无法进一步将样式应用于所有 TextBlock 元素。
【问题讨论】:
-
什么是“不同的情况”?
-
在某些窗口中我需要 TextBlock 有一个白色的前景,而在其他窗口中我需要它有一个黑色的前景,例如
-
您是否查看过“视觉状态”。您可以在模板中设置不同的可见状态,这些状态可以在代码中分配。查看上一个问题What is a visual state ...
标签: c# wpf xaml styles datatemplate