ApplicationBarIconButton为空。

21

为什么我的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>

appBarSave对象为空,尝试使用以下代码:

Initialize Component();
appbarSave.IsEnabled = true;

导致 NullReferenceException 异常。该对象仅在点击事件中起作用(如果启用):

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

我希望能够在开始时将保存按钮设置为禁用,稍后再启用它。

5个回答

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;
}

17

试试这个

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

太棒了!这个可以用! - F3RD3F

1

我使用一个可绑定的应用栏控件从这里下载链接在文章底部。

这使得生活更加轻松,避免了您不得不将代码放在代码后面的麻烦。


1
今天我犯了一个错误,x:Name被忽略了。
无论您在XAML中是否创建,ApplicationBar已经是页面的一部分了。不需要创建新的ApplicationBar,只需在代码后台文件中使用ApplicationBar属性即可。
Initialize Component();
ApplicationBar.IsEnabled = true;

0

我这样做,例如更改图标

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接