I have a Pivot control with two PivotItems . The XAML markup looks like this:
<Pivot x:Name="myPivot">
<PivotItem x:Name="pivot_item1" Header="header1">
<StackPanel x:Name="StackPanel1">
<TextBlock Text="page1"></TextBlock>
</StackPanel>
</PivotItem>
<PivotItem x:Name="pivot_item2" Header="header2">
<StackPanel x:Name="StackPanel2">
<Button x:Name="TestButton" Content="Test" Click="Button_Click"></Button>
</StackPanel>
</PivotItem>
</Pivot>
Now the problem is when I try to access the individual elements in code behind. For example in the OnNavigated
method accessing StackPanel1 would work OK but accessing StackPanel2 returns null.:
StackPanel sp1 = StackPanel1; // OK
StackPanel sp2 = Stackpanel2; // null
Accessing any element in the second PivotItem by its x:Name returns null. I thought it might be because the second pivot item wasn't initialized yet, so I created a Button in the second PivotItem and tried to access it by its x:Name in the click handler like this:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button b = TestButton; //null
Button b2 = (Button)sender; // OK
}
but this still returns null althought the button clearly is initialized. Can anyone please explain this to me and suggest a workaround? Thank you!
There is something wrong with your project or you have that Pivot inside another container. A Pivot should be the Top Container. It does not work well if is part of another top style container. You also might want to check the Constructor it should look like this
public MainPage()
{
this.InitializeComponent(); // check here as well to see if it declares every UI element correctly
this.NavigationCacheMode = NavigationCacheMode.Required;
}
Screen Shot of the Debug (as you can see , no nulls -- this is using your code you posted)
I suggest first creating a new WP8.1 runtime project and see if you can repeat your error.
I think that your second PivotItem is not yet loaded and control is not available. Add Loaded event to the pivot and try this code:
private void appPivot_LoadedPivotItem(object sender, PivotItemEventArgs e)
{
if ( e.Item.Name.CompareTo( "pivot_item1" ) == 0 )
{
StackPanel sp1 = StackPanel1;
}
else
{
StackPanel sp2 = StackPanel2;
}
}
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.