ApplicationBarIconButton为null

Jac*_*ble 21 windows-phone-7

为什么我的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>
Run Code Online (Sandbox Code Playgroud)

appBarSave对象为null,并尝试这样做:

Initialize Component();
appbarSave.IsEnabled = true;
Run Code Online (Sandbox Code Playgroud)

导致NullReferenceException.对象工作的唯一位置是click事件(如果我启用它):

private void appbarSave_Click(object sender, EventArgs e)
{
    ApplicationBarIconButton button = (ApplicationBarIconButton)sender;
    button.IsEnabled = false;
}
Run Code Online (Sandbox Code Playgroud)

我真的希望能够将保存按钮启动为禁用并稍后启用它.

Jac*_*cob 18

我记得以前运行到这个问题:有一个解释这里.一个简单的解决方法是在代码隐藏而不是xaml(就像这里)中实例化它.

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;
}
Run Code Online (Sandbox Code Playgroud)


小智 17

试试这个

Microsoft.Phone.Shell.ApplicationBarIconButton btn = ApplicationBar.Buttons[0] as Microsoft.Phone.Shell.ApplicationBarIconButton;
btn.IsEnabled = false;
Run Code Online (Sandbox Code Playgroud)