Reputation: 359
I want to update some text on a flyout. However, when I try to set its value in the code behind I get the error "The name 'dateChosen' does not exist in the current context".
Code behind:
private void updateDateBinding()
{
lstMenus.Visibility = Visibility.Visible;
dateChosen.Text = ""; // <-- Error here
}
Xaml code:
<ListView x:Name="lstMenus">
<!-- ...other code... -->
<TextBox x:Name="dateChosen" IsReadOnly="True"
Text="{Binding getDateChosen, Mode=TwoWay}"/>
<!-- ...other code... -->
</ListView>
Originally I was only going to use the PropertyChanged event to update 'dateChosen' but it did not update when calling that event. So I've decided to set the value explicitly instead, only to find this issue.
What confuses me is that 'lstMenus' can be altered exactly as I would expect. How can my ListView exist, but not the TextBox inside of it?
-
PS: I've cut most of superfluous code from this (Height/Width, Background, Alignment, etcetera) but I feel I should mention that the TextBox in question is pretty deeply nested in this chunk of code. The full inheritance is:
ListView(lstMenus) - ListView.ItemTemplate - DataTemplate - StackPanel - Grid - Grid - AppBarButton - AppBarButton.Flyout - Flyout - Grid - Grid - TextBox(dateChosen)
I've tried setting the 'x:Name' property for some of the intervening tags but always get the same "not in current context" issue when I try reaching them from the code behind.
Upvotes: 2
Views: 4975
Reputation: 31813
This question comes up from time to time. Look here: http://blog.jerrynixon.com/2012/09/how-to-access-named-control-inside-xaml.html
Since the control is in a generated container, it's actually no longer in scope. That's why you can't reference it. You will have to ask the ListView for the container, and then ask the container for the element. That blog article will explain the steps. It's not all that difficult.
Think about this, by the way, if you had 10 items in your ListView, wouldn't you have 10 items with that same name? You can't do that, of course. And, that's sort of why this problem exists. The ListView has to constrain the scope of the child item so it doesn't violate simple OOP.
Upvotes: 4