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

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?

Upvotes: 1

Views: 103

Answers (1)

Athari
Athari

Reputation: 34293

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.

Upvotes: 1

Related Questions