【问题标题】:Applying style to elements inside a DataTemplate将样式应用于 DataTemplate 中的元素
【发布时间】: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>

这适用于窗口中的所有其他文本块。

我还尝试使用

在代码隐藏中获取 DataTemplate
var myDataTemplate = (DataTemplate)this.Resources["dataTemp"];

但无法进一步将样式应用于所有 TextBlock 元素。

【问题讨论】:

  • 什么是“不同的情况”?
  • 在某些窗口中我需要 TextBlock 有一个白色的前景,而在其他窗口中我需要它有一个黑色的前景,例如
  • 您是否查看过“视觉状态”。您可以在模板中设置不同的可见状态,这些状态可以在代码中分配。查看上一个问题What is a visual state ...

标签: c# wpf xaml styles datatemplate


【解决方案1】:

不过,我不确定您的要求。但是为了从后面的代码中查找控件,我建议使用VisualTreeHelper。我通常使用这个辅助函数来做我的事情 -

public IEnumerable<T> FindVisualChildren<T>( DependencyObject depObj )
    where T : DependencyObject
{
  if( depObj != null )
  {
     for( int i = 0; i < VisualTreeHelper.GetChildrenCount( depObj ); i++ )
     {
        DependencyObject child = VisualTreeHelper.GetChild( depObj, i );
        if( child != null && child is T )
        {
           yield return (T)child;
        }

        foreach( T childOfChild in FindVisualChildren<T>( child ) )
        {
           yield return childOfChild;
        }
     }
  }
}

用法:

foreach (var textBlock in FindVisualChildren<TextBlock>(this))
{
       /*   Your code here  */
}

【讨论】:

    猜你喜欢
    • 2018-05-05
    • 2020-06-23
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 2014-12-08
    相关资源
    最近更新 更多