BindableApplicationBar.BindableApplicationBarButton.Attach C# (CSharp) Method

Attach() public method

Creates an associated ApplicationBarIconButton 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)
        {
            Debug.Assert(
                this.IconUri != null, "IconUri property cannot be null.");

            if (this.applicationBarIconButton != null)
            {
                return;
            }

            this.applicationBar = parentApplicationBar;
            
            this.applicationBarIconButton = 
                new ApplicationBarIconButton(this.IconUri)
                {
                    Text = string.IsNullOrEmpty(this.Text) ? "." : this.Text,
                    IsEnabled = this.IsEnabled
                };

            this.applicationBarIconButton.Click +=
                this.ApplicationBarIconButtonClick;

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

                throw;
            }
        }

Usage Example

        private void AttachButton(BindableApplicationBarButton button, int i)
        {
            if (button.GetBindingExpression(
                    FrameworkElement.DataContextProperty) == null &&
                button.GetValue(
                    FrameworkElement.DataContextProperty) == null)
            {
                button.DataContext = this.DataContext;
            }

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