在我的C#Windows Phone 8应用程序中,我有一个AppBar。我在这个AppBar上有两个图标,一个是新图标,还有一个是编辑图标。我想更改编辑图标,每当按下时更改为后退图标,然后每当再次按下时更改回编辑图标。我尝试过这个代码,但得到了一个nullReferenceException:
public static Uri addIcon = new Uri("/Assets/AppBar/new.png", UriKind.Relative);
public static Uri backIcon = new Uri("/Assets/AppBar/back.png", UriKind.Relative);
//Edit the projects
if (editMode.Equals(false))
{
//EditMode is off, enable edit mode and modify the editprojectMenuButton
editMode = true;
editprojectMenuButton.IconUri = backIcon;
editprojectMenuButton.Text = "finish";
} else
{
//EditMode is on, disable edit mode and modify the editprojectMenubutton
editMode = false;
editprojectMenuButton.IconUri = addIcon;
editprojectMenuButton.Text = "edit";
}
Xaml代码:
<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton x:Name="editprojectMenuButton" IconUri="/Assets/AppBar/edit.png" Text="Edit" Click="editprojectMenuButton_Click"/>
<shell:ApplicationBarIconButton x:Name="addprojectMenuButton" IconUri="/Assets/AppBar/new.png" Text="Add" Click="addprojectMenuButton_Click"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem x:Name="aboutButton" Text="About" Click="aboutButton_Click"/>
<shell:ApplicationBarMenuItem x:Name="howtoButton" Text="How To" Click="howtoButton_Click"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
备用应用程序条形码:
//Create the AppBar
ApplicationBar = new ApplicationBar();
ApplicationBar.Mode = ApplicationBarMode.Default;
ApplicationBar.IsMenuEnabled = true;
addprojectMenuBtn = new ApplicationBarIconButton(new Uri("BarIcons/add.png", UriKind.Relative));
addprojectMenuBtn.Text = "add";
addprojectMenuBtn.Click += addprojectMenuButton_Click;
editprojectMenuBtn = new ApplicationBarIconButton(new Uri("BarIcons/edit.png", UriKind.Relative));
editprojectMenuBtn.Text = "add";
editprojectMenuBtn.Click += editprojectMenuButton_Click;
ApplicationBar.Buttons.Add(addprojectMenuBtn);
ApplicationBar.Buttons.Add(editprojectMenuBtn);
当您在xaml中创建AppBar时,代码背后对Button的引用似乎为null
我正在用程序化的方式制作我的AppBar,但我还没有发现这样的问题:
ApplicationBar = new ApplicationBar();
ApplicationBar.Mode = ApplicationBarMode.Default;
ApplicationBar.IsMenuEnabled = false;
ApplicationBarIconButton addBtn = new ApplicationBarIconButton(new Uri("BarIcons/add.png", UriKind.Relative));
addBtn.Text = "Add";
addBtn.Click += addBtn_Click;
ApplicationBarIconButton infoBtn = new ApplicationBarIconButton(new Uri("BarIcons/info.png", UriKind.Relative));
infoBtn.Text = "Info";
infoBtn.Click += infoBtn_Click;
ApplicationBar.Buttons.Add(addBtn);
ApplicationBar.Buttons.Add(infoBtn);
您还可以在那里添加菜单项以及您想要的内容。然后,如果ApplicationBarIconButton是"全局"变量,您可以随时更改它,并且它可以工作
编辑-一些解释
在这里,我发现了类似的问题,并在这个博客上解释
还有一个代码可以工作:
Microsoft.Phone.Shell.ApplicationBarIconButton btn = ApplicationBar.Buttons[0] as Microsoft.Phone.Shell.ApplicationBarIconButton;
btn.IconUri = backIcon;
btn.Text = "My button";