Why is my XAML ToggleButton invisible to the code-behind?

113 views Asked by At

I have a ToggleButton in MainPage.xaml:

<ToggleButton x:Name="ColorToggle" Background="{Binding Background, ElementName=LayoutRoot}" ToolTipService.ToolTip="Change Toolbar Color">

...yet when I try to access it from MainPage.xaml.cs:

private void SaveAppBarColorSelected(object sender, TappedRoutedEventArgs e)
{
    PhotraxUtils.SetLocalSetting(PhotraxConsts.APPBARBUTTON_COLOR, ColorToggle.Background.ToString());
}

...I get, "The name 'ColorToggle' does not exist in the current context"

Why is that?

1

There are 1 answers

0
Athari On BEST ANSWER

Only controls from the root context are available in code-behind. If you place your named control inside a template, it won't be available. You can traverse the controls tree using VisualTreeHelper and other methods in this case.

Or better yet, just use MVVM.