简体   繁体   English

为什么我的XAML ToggleButton对隐藏的代码不可见?

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

I have a ToggleButton in MainPage.xaml: 我在MainPage.xaml中有一个ToggleButton:

<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: ...但是当我尝试从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 " ...我得到,“ 名称'ColorToggle'在当前上下文中不存在

Why is that? 这是为什么?

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. 在这种情况下,您可以使用VisualTreeHelper和其他方法遍历控件树。

Or better yet, just use MVVM. 或更妙的是,只需使用MVVM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM