BindableApplicationBar.BindableApplicationBarMenuItem.Attach C# (CSharp) Method

Attach() public method

Creates an associated ApplicationBarMenuItem and attaches it to the specified application bar.
public Attach ( Microsoft.Phone.Shell.ApplicationBar parentApplicationBar, int i ) : void
parentApplicationBar Microsoft.Phone.Shell.ApplicationBar /// The application bar to attach to. ///
i int /// The index at which the associated /// will be inserted. ///
return void
        public void Attach(ApplicationBar parentApplicationBar, int i)
        {
            if (this.applicationBarMenuItem != null)
            {
                return;
            }

            this.applicationBar = parentApplicationBar;
            this.applicationBarMenuItem =
                new ApplicationBarMenuItem
                {
                    Text = string.IsNullOrEmpty(this.Text) ? "." : this.Text,
                    IsEnabled = this.IsEnabled
                };

            this.applicationBarMenuItem.Click +=
                this.ApplicationBarMenuItemClick;

            try
            {
                this.applicationBar.MenuItems.Insert(
                    i, this.applicationBarMenuItem);
            }
            catch (InvalidOperationException ex)
            {
                // Up to 50 menu items supported in ApplicationBar.MenuItems
                // at the time of this writing.
                if (ex.Message == "Too many items in list" &&
                    Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                throw;
            }
        }

Usage Example

        private void AttachMenuItem(
            BindableApplicationBarMenuItem menuItem, int i)
        {
            if (menuItem.GetBindingExpression(
                    FrameworkElement.DataContextProperty) == null &&
                menuItem.GetValue(
                    FrameworkElement.DataContextProperty) == null)
            {
                menuItem.DataContext = this.DataContext;
            }

            menuItem.Attach(this.applicationBar, i);
        }