A simple solution is to use XAML to define your buttons and ViewModel (MVVM pattern) to control the visibilities of these buttons, and this can avoid creating buttons in code and complicated logic to control which button to display.
First, define all the buttons might be used in CommandBar:
<Page.BottomAppBar>
<CommandBar>
<!--buttons of group1-->
<AppBarButton Icon="Icon1" Label="button1"/>
...
<!--buttons of group2-->
<AppBarButton Icon="Icon2" Label="button2"/>
...
<!--buttons of group3-->
<AppBarButton Icon="Icon3" Label="button3"/>
</CommandBar>
</Page.BottomAppBar>
Then define a property in the ViewModel, such as:
public class PageViewModel : INotifyPropertyChanged
{
...
public int CommandGroup
{
get { return _commandGroup; }
set { _commandGroup = value; NotifyPropertyChanged("CommandGroup"); }
}
}
This CommandGroup property is used to control the show/hide of buttons, for example, setting CommandGroup = 1 to show buttons in group1 and hide buttons in other groups, and setting CommandGroup = 2 to show buttons in group2 and hide buttons in other groups, which group1 and group2 here are just logical groups.
Then define a converter to convert the value of CommandGroup property to Visibility:
public class CommandGroupToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return (System.Convert.ToInt32(value) == System.Convert.ToInt32(parameter)) ? Visibility.Visible : Visibility.Collapsed;
}
}
And finally, bind this CommandGroup property to all the buttons in CommandBar (copy and paste things):
<Page.Resources>
<c:CommandGroupToVisibilityConverter x:Key="MyConverter"/>
</Page.Resources>
<Page.BottomAppBar>
<CommandBar>
<!--buttons of group1-->
<AppBarButton
Icon="Icon1" Label="button1"
Visibility="{Binding CommandGroup, Converter={StaticResource MyConverter}, ConverterParameter=1}"/>
<!--buttons of group2-->
<AppBarButton
Icon="Icon2" Label="button2"
Visibility="{Binding CommandGroup, Converter={StaticResource MyConverter}, ConverterParameter=2}"/>
<!--buttons of group3-->
<AppBarButton
Icon="Icon3" Label="button3"
Visibility="{Binding CommandGroup, Converter={StaticResource MyConverter}, ConverterParameter=3}"/>
</CommandBar>
</Page.BottomAppBar>
Note that when CommandGroup == 2, then all buttons with ConverterParameter=2 will display and others are gone.
This might be very useful in where there are several views in one page (like a Pivot) and each of them has its different group of command buttons.