2

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

3
  • @Slugster,I have 4 Different Text Box inside the Data Template and I want to swap the Visibiliti Option from the different Button Clicks. Commented May 27, 2010 at 12:21
  • 1
    Your question as is don't make sense. To make the textblock named myTextBox collapsed, just change its visibility property yo collapsed. You have a reference to it since you named it. This can be done in code behind where ever you want to do it. Commented May 27, 2010 at 16:04
  • 2
    @Wallstreet Programmer, We can't access a Textbox by It's name if it is present inside the DataTemplate. Suggest you to try it yourself. Commented May 28, 2010 at 11:43

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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 } 

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.