Reputation: 7900
I have this MenuBar
in my application:
<Menu Grid.Row="0" Height="22" Name="menu1" HorizontalAlignment="Stretch" VerticalAlignment="Top" >
<MenuItem Header="File" />
<MenuItem Header="Youtube">
</MenuItem>
<MenuItem Header="Help" />
</Menu>
And i want to add items to the Youtube MenuItem
dynamic ,something like this:
MenuItem menu = (MenuItem)sender;
ItemCollection items = menu.Items;
items.Clear();
if (YouTubeAuth.CreateInstance().IsLogin())
{
MenuItem refreshItem = new MenuItem();
refreshItem.Header = "Refresh";
refreshItem.Click += DidPressRefresh;
items.Add(refreshItem);
MenuItem logouttItem = new MenuItem();
logouttItem.Header = "Signout";
logouttItem.Click += DidPressLogout;
items.Add(logouttItem);
}
else
{
MenuItem loginItem = new MenuItem();
loginItem.Header = "Login";
loginItem.Click += DidPressLogin;
items.Add(loginItem);
}
It say if you login show logout and refresh otherwise shot login.
I try to add this method to Click="DidPressDeleteAllFavorites"
of the Youtube MenuItem
but it won't work.
Any idea how to fix it? what i do wrong?
Upvotes: 0
Views: 1961
Reputation: 5420
if you are using the MVVM-pattern
<MenuItem Header="Youtube" ItemsSource="{Binding yourProperty}"/>
if you are working with code-behind
XAML
<MenuItem Header="Youtube" Name="myYoutube"/>
Code-behind
myYoutube.ItemsSource=yourMenuItems;
the problem in your code is in my opinion you just need to call your Event Code on on startup because your Youtube has no subMenuitem on begin or you could also call UpdateLayout()
in your event this could also maybe fix it
Codebehind
public partial class MainWindow : Window
{
bool test = false;
public MainWindow()
{
InitializeComponent();
MenuItem_Click(myYouTube, null);
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
var mymenuitem = sender as MenuItem;
MenuItem menu = (MenuItem)sender;
ItemCollection items = menu.Items;
items.Clear();
if (test)
{
MenuItem refreshItem = new MenuItem();
refreshItem.Header = "Refresh";
//refreshItem.Click += DidPressRefresh;
items.Add(refreshItem);
MenuItem logouttItem = new MenuItem();
logouttItem.Header = "Signout";
//logouttItem.Click += DidPressLogout;
items.Add(logouttItem);
test = false;
}
else
{
MenuItem loginItem = new MenuItem();
loginItem.Header = "Login";
//loginItem.Click += DidPressLogin;
items.Add(loginItem);
test = true;
}
}
}
XAML
<Menu Height="23" HorizontalAlignment="Left" Margin="84,66,0,0" Name="menu1" VerticalAlignment="Top" Width="200">
<MenuItem Header="File" />
<MenuItem Header="Youtube" Name="myYouTube" Click="MenuItem_Click">
</MenuItem>
<MenuItem Header="Help" />
</Menu>
Upvotes: 1