views:

91

answers:

2

Hi,

I have Few TextBlock inside the Data template as follow:

 <DataTemplate>
    <StackPanel x:Name="stackPanelItems" Orientation="Horizontal">
        <TextBlock  x:Name="myTextBox" HorizontalAlignment="Center" VerticalAlignment="Top"   FontSize="14" />
    </StackPanel>
  </DataTemplate>

Now we need to Make the myTextBox Collsapsed in some scenarios but dont want to use the loaded or click event and then access the control via sender.

Can I used any other method or way?

Thanks,

Subhen

+1  A: 

Unfortunately, there's way to do this as simple as accessing a named object. Assuming that you're using binding to fill this Data Template, one option would be to iterate through the child objects of the parent control and check the text fields against a known value. Slightly cleaner might be to make use of the Tag property (which can be bound to any object) and make comparisons that way.

Another option (the one I use most frequently for things like this) would be to add a property to the object that you're binding to and bind that property to visibility (using a converter if necessary). For example, if you're currently binding to an ObservableCollection< string >, change the binding to an ObservableCollection< StringWithVisibility > where StringWithVisibility looks like:

public class StringWithVisibility
{
    public string Text {get; set;}
    public bool IsVisible {get; set;}
}

And then your template looks like:

<DataTemplate>
    <StackPanel x:Name="stackPanelItems" Orientation="Horizontal">
        <TextBlock Text="{Binding Text}" Visibility={Binding IsVisible, Converter={StaticResource BoolVisibilityConverter}} />
    </StackPanel>
</DataTemplate>

And you have created the appropriate IValueConverter as a resource. If you're not familiar with converters, the docs are here: http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter(VS.95).aspx

Raumornie
+1  A: 

The converter is the best approach, but to answer your question, you can access the control this way, in code behind:

TextBox myTextbox = GetTemplateChild("myTextbox") as Textbox;

if (myTextbox != null) { // do something }

kmacmahon