我找不到在主页资源和样式中定义的按钮。在访问该按钮后,我想将其视觉状态更改为按下。这是我在代码隐藏(MainPage.xaml.cs)中尝试的:
private void OnShowPopupButtonClick(object sender, RoutedEventArgs e)
{
this.myPopup.IsOpen = !this.myPopup.IsOpen;
//attempt at accessing button resource to change state
if ((this.myPopup.IsOpen))
{
this.HomeButton.Controls.Style = this.Resources["PivotStyle1"] as Style;
VisualStateManager.GoToState(HomeButton, "Pressed", true);
}
}
HomeButton 所在的层次结构(在 MainPage.xaml 中)如下:
<phone:PhoneApplicationPage.Resources>
...
<Style x:Key="PivotStyle1" TargetType="controls:Pivot">
....
<Setter Property="Template">
...
<Setter.Value>
<ControlTemplate TargetType="controls:Pivot">
...
<Grid>
<ContentPresenter>
<StackPanel>
<StackPanel>
<Button x:Name="HomeButton" Style="{StaticResource ButtonStyle1}" Click="OnShowPopupButtonClick" >
.....
.....
这里是我在 layoutroot 中调用我的风格的地方:
<Grid x:Name="LayoutRoot">
<controls:Pivot x:Name="MainPivotControl" Title="MyApp" Style="{StaticResource PivotStyle1}" FontFamily="myFont">
...
...
因此,当我尝试构建应用程序时,会弹出一条错误消息,提示 HomeButton 在当前上下文中不存在。另一个错误消息说它没有定义或扩展方法。有谁知道我在后面的代码中可能做错了什么?这几天我一直在浏览网页并浏览一些教程,但没有任何帮助。谢谢
编辑:这是用户“nit”建议的代码:但断点显示 HomeButton 仍未找到。
private void OnShowPopupButtonClick(object sender, RoutedEventArgs e)
{
this.myPopup.IsOpen = !this.myPopup.IsOpen;
//attempt at accessing button resource to change state
if ((this.myPopup.IsOpen))
{
//This section will help locate and assign HomeButton then event function will launch
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(MainPivotControl); i++)
{
var child = VisualTreeHelper.GetChild(MainPivotControl, i);
if (child is Button)
{
var myHomeButton = child as Button;
//This is where the event procedure will be given
if (myHomeButton.Name == "HomeButton")
{
VisualStateManager.GoToState(myHomeButton, "Pressed", true);
break;
}
}
}
}
else
{
//This section will help locate and assign HomeButton then event function will launch
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(MainPivotControl); i++)
{
var child = VisualTreeHelper.GetChild(MainPivotControl, i);
if (child is Button)
{
var myHomeButton = child as Button;
//This is where the event procedure will be given
if (myHomeButton.Name == "HomeButton")
{
VisualStateManager.GoToState(myHomeButton, "Pressed", false);
break;
}
}
}
}
}