简体   繁体   中英

Applying style to elements inside a DataTemplate

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>

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.

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>

This worked for all other TextBlocks in the window.

I also attempted to get the DataTemplate in the codebehind using

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

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

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

Usage:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM