2
votes

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.

1
what are "the different circumstances" ?Cybermaxs
In some windows I need the TextBlock to have a white Foreground, and in others I need it to have a black Foreground, for examplebinncheol
Have you looked into "Visual States". You can in your template setup different visible states, which can be assigned in code. Check out previous question What is a visual state ...Spevy

1 Answers

1
votes

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