ApplicationBarIconButton is null

烂漫一生 提交于 2020-01-01 01:16:29

问题


Why is my ApplicationBarIconButton null?

<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" x:Name="appBar">
        <shell:ApplicationBarIconButton x:Name="appbarSave"
          IconUri="/Icons/appbar.save.rest.png Text="Save" IsEnabled="False"
          Click="appbarSave_Click" />
    </shell:Application Bar>
</phone:PhoneApplicationPage.ApplicationBar>

The appBarSave object is null, and trying this:

Initialize Component();
appbarSave.IsEnabled = true;

Results in a NullReferenceException. The only place the object works is in the click event (if I enable it):

private void appbarSave_Click(object sender, EventArgs e)
{
    ApplicationBarIconButton button = (ApplicationBarIconButton)sender;
    button.IsEnabled = false;
}

I would really like to be able to start the save button as disabled and enabled it later.


回答1:


I remember running into this issue before: there's an explanation here. An easy workaround is just to instantiate it in code-behind rather than xaml (like here).

private ApplicationBarIconButton SaveEdit;
private void InitAppBar()
{
     ApplicationBar appBar = new ApplicationBar();

     SaveEdit = new ApplicationBarIconButton(new Uri("images/appbar.check.rest.png", UriKind.Relative));
     SaveEdit.Click += new EventHandler(OnClick_Check);
     SaveEdit.Text = Strings.Save_button;
     appBar.Buttons.Add(SaveEdit);

     ApplicationBarIconButton CancelEdit = new ApplicationBarIconButton(new Uri("images/appbar.close.rest.png", UriKind.Relative));
     CancelEdit.Click += new EventHandler(OnClick_Cancel);
     CancelEdit.Text = Strings.Cancel_button;
     appBar.Buttons.Add(CancelEdit);

     ApplicationBar = appBar;
}



回答2:


try this

Microsoft.Phone.Shell.ApplicationBarIconButton btn = ApplicationBar.Buttons[0] as Microsoft.Phone.Shell.ApplicationBarIconButton;
btn.IsEnabled = false;



回答3:


I use a bindable app bar control from here The download link is at the bottom of the article.

Makes life much easier and saves you from having to put code in the code behind.




回答4:


I made this mistake today, the x:Name is ignored.

The ApplicationBar is part of the page already, whether you create it in XAML or not. There is no need to create a new one. Just use the ApplicationBar property in the code behind file.

Initialize Component();
ApplicationBar.IsEnabled = true;



回答5:


I do it so, example for change icon

ApplicationBarIconButton btn =  (ApplicationBarIconButton)ApplicationBar.Buttons[0];
btn.IconUri = new Uri("/images/play.png", UriKind.Relative);


来源:https://stackoverflow.com/questions/5334574/applicationbariconbutton-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!