将样式应用于DataTemplate中的元素 [英] Applying style to elements inside a DataTemplate

查看:92
本文介绍了将样式应用于DataTemplate中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UserControl,它仅在DataTemplate中包含一个TextBlock和TextBox。这是通过以下方式完成的:

I have a UserControl which simply contains a TextBlock and TextBox inside a DataTemplate. This is done in the following way:

<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的宽度。

I need to be able to apply different styles to the TextBlock/TextBox under different circumstances. For example in certain instances I would like to be able to apply a white Foreground to the TextBlock or change the width of a TextBox.

我尝试了几种不同的方法:
在使用控件的窗口中,我设置了TextBlock的样式:

I have tried a few different approaches: In the window where the control is being used I have set the style for the TextBlock:

<Style TargetType="{x:Type TextBlock}" >
    <Setter Property="Foreground" Value="White" />
</Style>

此功能适用于窗口中的所有其他TextBlock。

This worked for all other TextBlocks in the window.

我还尝试使用

var myDataTemplate = (DataTemplate)this.Resources["dataTemp"];

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

But was unable to get any further in applying the style to all the TextBlock elements.

推荐答案

不过,我不确定您的要求。但是,为了从代码后面查找控件,我建议使用 VisualTreeHelper 。我通常使用此辅助函数来完成任务-

I am not sure of your requirement though. But for finding controls from code behind, i would recommend to use VisualTreeHelper. I generally used this helper function to do my stuff -

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  */
}

这篇关于将样式应用于DataTemplate中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆