ContextMenu MenuItems adding continuously on Click event - wpf

on click event ,I have return adding of menu items to contextmenu.but on clicking more than once it keeps adding the menu items to the contextmenu. Here the below code am using for it.
<StackPanel Grid.Row="13" Orientation="Horizontal" FlowDirection="LeftToRight">
<Button Name="btnMobile" Content="Home" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0 0 20 0" Width="70"></Button>
<!--<extToolkit:DropDownButton x:Name="ddBtnMobile" VerticalAlignment="Top" Width="30" HorizontalAlignment="Right" Margin="0 0 30 0" Height="20"/>-->
<Button HorizontalAlignment="Left" Name="ddBtnMobile" Width="30" Click="OnddBtnMobileClick" Margin="0,0,0,5" >
<Button.Content>
<Path x:Name="btnArrow3" Margin="4" VerticalAlignment="Center" Width="10" Fill="#FF527DB5" Stretch="Uniform" HorizontalAlignment="Right" Data="F1 M 301.14,-189.041L 311.57,-189.041L 306.355,-182.942L 301.14,-189.041 Z "/>
</Button.Content>
<Button.ContextMenu>
<ContextMenu Name="cMenu">
</ContextMenu>
</Button.ContextMenu>
</Button>
</StackPanel>
code am using is below
private void OnddBtnMobileClick(object sender, RoutedEventArgs e)
{
mnItem = new MenuItem();
mnItem.Header ="B1";
cMenu.Items.Add(mnItem);
mnItem = new MenuItem();
mnItem.Header ="A1";
cMenu.Items.Add(mnItem);
mnItem = new MenuItem();
mnItem.Header="B 2";
cMenu.Items.Add(mnItem);
cMenu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClick));
}
private void OnMenuItemClick(object sender, RoutedEventArgs e)
{
RoutedEventArgs args = e as RoutedEventArgs;
MenuItem item = args.OriginalSource as MenuItem;
string header = item.Header.ToString();
if (header == "Business")
{
btnMobile.Content = header;
}
else if (header == "Assistant")
{
btnMobile.Content = header;
}
}
how to solve my issue.. Is there any better way of writing the above logic. i.e., adding menu items of context menu at run time.

add a boolean data member which will check if the sub menu's were already added
private void OnddBtnMobileClick(object sender, RoutedEventArgs e)
{
if(alreadyAdded == true)
return;
alreadyAdded = true;
mnItem = new MenuItem();
mnItem.Header ="B1";
cMenu.Items.Add(mnItem);
mnItem = new MenuItem();
mnItem.Header ="A1";
cMenu.Items.Add(mnItem);
mnItem = new MenuItem();
mnItem.Header="B 2";
cMenu.Items.Add(mnItem);
cMenu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClick));
}

Add the following code in the button click event's starting.
cMenu = new cMenu();
Thats you need to create a new instance.
Thanks,

Related

How to display an image with openfiledialog and label wpf

im creating a program to display any image with openfiledialog and a label(this one to display the image) i also added a textbox to show the image path
private void button_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".png";
dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
textBox.Text = filename;
Ima = new Image();
Ima.Source = new BitmapImage(new Uri(#dlg.FileName));
label.Content = Ima;
}
heres the xaml code of the label:
<Label x:Name="label1" HorizontalAlignment="Left" Height="78" Margin="107,180,0,0" VerticalAlignment="Top" Width="344"/>
The problem with this is that when i choose the image i want to display, the label doesn't show it.
Xaml File
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Image Name="servicePhoto" Height="100" Width="100" Stretch="Fill" />
<Button Height="40" HorizontalAlignment="Left" Name="btnLoad" VerticalAlignment="Center" Width="200" Click="ServiceImage_Click">Choose Image</Button>
</StackPanel>
.cs File
private void ServiceImage_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
servicePhoto.Source = new BitmapImage(new Uri(op.FileName));
}
}

how to bind listview selected item to textbox dynamically in wpf

I have 2 columns in my Grid. I will create Button and textbox dynamically in each row. For the dynamic button click, I will show one popup window. The Popup window has some ListviewItems. this is my requirement:
1.If I select any Listview item, it should be displayed on the corresponding textbox.
for example, If it is in the 3rd row, I want to bind the ListviewItem in textbox which is positioned in (Row3, Column1)
this is my xaml:
<Grid>
<DockPanel HorizontalAlignment="Left" Height="165" Margin="40,100,0,0" VerticalAlignment="Top" Width="620">
<ScrollViewer>
<Grid x:Name="grid1" Height="auto" Width="580"/>
</ScrollViewer>
</DockPanel>
<Button x:Name="btn_addnewrow" Content="Add" HorizontalAlignment="Left" Margin="69,43,0,0" VerticalAlignment="Top" Width="89" Height="31" Click="btn_addnewrow_Click"/>
<Popup Name="popup" IsOpen="False" Placement="Mouse" VerticalOffset="15" HorizontalOffset="0" Margin="124,122,107,65">
<Border BorderBrush="Black" BorderThickness="1" Background="Coral">
<StackPanel Orientation="Horizontal" Height="143">
<ListView Margin="10,10,0,0" Name="ListView1" HorizontalAlignment="Left"
VerticalAlignment="Top" Width="194" Height="133" MouseDoubleClick="ListView1_MouseDoubleClick">
<ListViewItem Content="Coffie"></ListViewItem>
<ListViewItem Content="Tea"></ListViewItem>
<ListViewItem Content="Orange Juice"></ListViewItem>
<ListViewItem Content="Milk"></ListViewItem>
<ListViewItem Content="Iced Tea"></ListViewItem>
<ListViewItem Content="Mango Shake"></ListViewItem>
</ListView>
</StackPanel>
</Border>
</Popup>
</Grid>
and this is my code:
public partial class DummyTypeofControl : Window
{
public DummyTypeofControl()
{
InitializeComponent();
}
public int count = 0;
public Button btn1;
public Button btn2;
public TextBox txt1;
private void btn_addnewrow_Click(object sender, RoutedEventArgs e)
{
//Creating Rows..
RowDefinition row0 = new RowDefinition();
row0.Height = new GridLength(40);
grid1.RowDefinitions.Add(row0);
//Creating columns..
ColumnDefinition col0 = new ColumnDefinition();
ColumnDefinition col1 = new ColumnDefinition();
col0.Width = new GridLength(50);
col1.Width = new GridLength(70);
grid1.ColumnDefinitions.Add(col0);
grid1.ColumnDefinitions.Add(col1);
int i = count;
//1st Column button
btn1 = new Button();
btn1.Margin = new Thickness(10, 10, 0, 0);
btn1.BorderThickness = new Thickness(0);
btn1.Name = "btn1_" + i;
Grid.SetRow(btn1, i);
Grid.SetColumn(btn1, 0);
btn1.Click += btnBindList_Click;
grid1.Children.Add(btn1);
//2nd column Textbox
txt1 = new TextBox();
txt1.Margin = new Thickness(10, 10, 0, 0);
txt1.Name = "txt" + i;
Grid.SetRow(txt1, i);
Grid.SetColumn(txt1, 1);
grid1.Children.Add(txt1);
count++;
}
private void btnBindList_Click(object sender, RoutedEventArgs e)
{
popup.IsOpen = true;
}
private void ListView1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
?
?
?
?
popup.IsOpen = false;
}
}
I want to take the rows count and bind listview itms to the corresponding rows textbox dynamically.. i dont know how to continue further.. could any one please help me?
Did not quite understand what you wanted, but give this a try.. a bit unconventional.
private void btn_addnewrow_Click(object sender, RoutedEventArgs e)
{
.....
//let the button know about the textbox
btn1.Tag = txt1;
}
Then, everytime you click on
private void btnBindList_Click(object sender, RoutedEventArgs e)
{
//get the linked textbox and keep it stored int txt1
txt1 = ((Button)sender).Tag as TextBox;
popup.IsOpen = true;
}
Then, when you click on on the listview
private void ListView1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
txt1.Text = (ListView1.SelectedItem as ListViewItem).Content.ToString();
popup.IsOpen = false;
}
There are better and cleaner ways to do this

MediaElement Class Is Not Play the Media file in WPF Application

MainWindow.Xaml
<MediaElement Margin="10,10,10,0 " Name="McMediaElement" Width="450" Height="250" LoadedBehavior="Manual" Stretch="Fill"
MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded" UnloadedBehavior="Stop" />
<Label Grid.Column="1" Grid.Row="1" Height="28" Margin="82,0,99,3.52"
Name="FileNameLabel" VerticalAlignment="Bottom" Background="LightGreen">
</Label>
<Button Height="23" Name="BrowseButton" Width="113" Grid.Column="1" HorizontalAlignment="Right"
Margin="0,0,182,7.04" Grid.Row="1" VerticalAlignment="Bottom" Grid.ColumnSpan="2"
FontWeight="Bold" Click="BrowseButtonClick">
Browse a Media
</Button>
When Click BrowseButton Its get the file from open Dialog box and it put into the Lable control as FileNameLabel
private void BrowseButtonClick(object sender, RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
dlg.InitialDirectory = "c:\\";
dlg.Filter = "Media files (*.wmv)|*.wmv|All Files (*.*)|*.*";
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedFileName = dlg.FileName;
FileNameLabel.Content = selectedFileName;
McMediaElement.Source = new Uri(selectedFileName);
McMediaElement.UpdateLayout();
McMediaElement.Play();
}
}
private void Element_MediaOpened(object sender, EventArgs e)
{
timelineSlider.Maximum = McMediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
}
// When the media playback is finished. Stop() the media to seek to media start.
private void Element_MediaEnded(object sender, EventArgs e)
{
McMediaElement.Stop();
}
its does not play the media file.so Plaese Suggest what the problem in code.

How to know in Listbox which ListItem button is clicked?

I have Listbox:
<ListBox x:Name="FriendsRequestList">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel>
<TextBlock Text="{Binding FullName}" Foreground="#FF316DCB"/>
<TextBlock Text="{Binding RequestText}" />
<StackPanel Orientation="Horizontal">
<Button Name="Accept" Content="Accept" Click="Accept_Click" Foreground="#FF28901F" Background="#FFB4D8BA"/>
<Button Name="Decline" Content="Decline" Click="Decline_Click" Foreground="#FF28901F" Background="#FFB4D8BA"/>
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</Listbox>
And I try these in code:
private void Accept_Click(object sender, RoutedEventArgs e)
{
Button clickedButton = sender as Button;
StackPanel st1 = clickedButton.Parent as StackPanel;
StackPanel st2 = st1.Parent as StackPanel;
StackPanel st3 = st2.Parent as StackPanel;
object parentControl = st3.Parent;
object obj = FriendsRequestList.Items[3];
int index1 = FriendsRequestList.Items.IndexOf(obj);
int index2 = FriendsRequestList.SelectedIndex;
int SenderId = FriendRequests.ElementAt(index).SenderID;
UserServices.FriendRequestAccept(this, SenderId);
UserServices.GetRequests(this);
}
index2 is -1, and parentControl is null. Why ListItem.SelectedIndex is -1?
And how can I know which ListItem button is clicked ?
The ListBox.SelectedIndex property is probably -1 because the Button is intercepting the click event and it is not being propagated to the ListBox. Anyway, you don't need the index to do what you're trying to do.
Let's say you set the ItemsSource as follows:
FriendsRequestList.ItemsSource = FriendRequests;
Now, assuming FriendRequests is some sort of collection containing FriendRequest objects, each of which contains the properties FullName, RequestText etc., modify the click handler to
private void Accept_Click(object sender, RoutedEventArgs e)
{
FriendRequest req = ( sender as Button ).DataContext as FriendRequest;
int senderID = req.SenderID;
...
}

Why doesn't this event work correctly?

i have two hyperlink in my code that contains image when i clear second one the first work but when both of them wrote like this the btnClose work as the btnnew . it meanse the event (btnAdd_Click) work for both of them and i dont know why
<HyperlinkButton x:Name="btnClose" Click="btnClose_Click">
<HyperlinkButton.RenderTransform>
<TranslateTransform />
</HyperlinkButton.RenderTransform>
<Canvas>
<Image Source="/ITStock;component/Images/undo.png" Height="20" Width="20"Margin="10,5,0,0"/>
</Canvas>
</HyperlinkButton>
<HyperlinkButton x:Name="btnNew" Click="btnAdd_Click" >
<HyperlinkButton.RenderTransform>
<TranslateTransform />
</HyperlinkButton.RenderTransform>
<Canvas>
<Image Source="/ITStock;component/Images/edit_add.png" Height="20" Width="20" Margin="45,5,0,0"/>
</Canvas>
</HyperlinkButton>
private void btnClose_Click(object sender, RoutedEventArgs e)
{
HtmlPage.Window.Invoke("OpenMainPage");
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
stock = new SR_BLStock.Stock();
if (stock != null)
{
dgStock1.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.Collapsed;
Grid grUsc = new Grid();
grUsc.Margin = new Thickness(50);
Border b = new Border();
b.Name = "uscBorder";
b.Background = new SolidColorBrush(Colors.Black);
b.Opacity = 0.6;
NewStock usc = new NewStock(stock);
dgStock1.IsEnabled = false;
dg.IsEnabled = false;
grUsc.Children.Add(usc);
LayoutRoot.Children.Add(grUsc);
}
}

Resources