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));
}
}
Related
i have a image control in wpf c#.
<Image x:Name="icon01" MouseDown="icon_MouseDown" Cursor="Hand" Source="FavIcon\01.png" Height="48" Width="48" Margin="10"/>
How can I save the image (FavIcon\01.png) to file on my PC? i use c# .net 4.0.
use the icon01.Source(ImageSource) to create a FileStream via the PngBitmapEncoder, here an example using a SaveFileDialog
private void icon_MouseDown(object sender, MouseButtonEventArgs e)
{
try
{
var saveFileDialog = new SaveFileDialog()
{
Filter = "Image Files (*.bmp, *.png, *.jpg)|*.bmp;*.png;*.jpg"
};
if (saveFileDialog.ShowDialog() == true)
{
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)icon01.Source));
using (FileStream stream = new FileStream(saveFileDialog.FileName, FileMode.Create))
encoder.Save(stream);
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
and the Xaml is the Same :
<Grid>
<Image x:Name="icon01" MouseDown="icon_MouseDown" Cursor="Hand" Source="FavIcon\01.png" Height="48" Width="48" Margin="10"/>
</Grid>
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,
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.
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);
}
}
I am creating a set of images dynamically and putting them into a Stack Panel like this :-
Image image = new Image();
image.Name = "image_" + iCounter;
image.Height = 100;
image.Width = 100;
image.Source = bitmap;
image.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
image.Stretch = Stretch.Fill;
image.VerticalAlignment = VerticalAlignment.Top;
//image.MouseDown += new MouseButtonEventHandler(image_MouseDown);
image.ToolTip = "Right-Click for Options";
image.ContextMenu = GetContextMenu();
Separator separator = new Separator();
separator.Name = "separator_" + iCounter;
AddImagesStackPanel.Children.Add(image);
AddImagesStackPanel.Children.Add(separator);
iCounter++;
Then in the Context Menu I have this code :-
private System.Windows.Controls.ContextMenu GetContextMenu()
{
System.Windows.Controls.MenuItem mi1;
System.Windows.Controls.MenuItem mi2;
System.Windows.Controls.ContextMenu _contextMenu = new System.Windows.Controls.ContextMenu();
mi1 = new System.Windows.Controls.MenuItem();
mi1.Header = "Show Normal Size";
mi1.Click += new RoutedEventHandler(ContextMenuItem1_Click);
mi2 = new System.Windows.Controls.MenuItem();
mi2.Header = "Remove image";
mi2.Click += new RoutedEventHandler(ContextMenuItem2_Click);
_contextMenu.Items.Add(mi1);
_contextMenu.Items.Add(mi2);
return _contextMenu;
}
Now I wish to get the selected item when the user right clicks on an image and I have this code :-
private void ContextMenuItem2_Click(object sender, RoutedEventArgs e)
{
object obj = e.OriginalSource;
string imageName = ((System.Windows.Controls.Image)obj).Name;
string[] split = imageName.Split('_');
imageUploads.RemoveAt(Convert.ToInt32(split[1]));
DisplayImagesInStackPanel(imageUploads);
}
But obj does not contain the name of the image since its a RoutedEventArgs. Is there any way I can get the selected item in the context menu?
After discussing this in the comments this should work:
// The binding source.
private readonly ObservableCollection<BitmapImage> _imageList = new ObservableCollection<BitmapImage>();
public ObservableCollection<BitmapImage> ImageList
{
get { return _imageList; }
}
How to display this and set up the ContextMenu:
<ItemsControl ItemsSource="{Binding ImageList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding}" Width="100" Height="100"
HorizontalAlignment="Left" Stretch="Fill"
VerticalAlignment="Top" ToolTip="Right-Click for Options">
<Image.ContextMenu>
<ContextMenu>
<MenuItem Header="Show Normal Size" Click="Image_CM_ShowNormalSize_Click"
Tag="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget}"/> <!-- The placement target is the object to which the context menu belongs, i.e. the image -->
<MenuItem Header="Remove Image" Click="Image_CM_RemoveImage_Click"
Tag="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.DataContext}"/> <!-- The DataContext of the Image is the BitmapImage, which should be removed from the list -->
</ContextMenu>
</Image.ContextMenu>
</Image>
<Separator/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
What the handlers might look like:
private void Image_CM_ShowNormalSize_Click(object sender, RoutedEventArgs e)
{
Image img = (sender as FrameworkElement).Tag as Image;
img.Width = (img.Source as BitmapImage).PixelWidth;
img.Height = (img.Source as BitmapImage).PixelHeight;
}
private void Image_CM_RemoveImage_Click(object sender, RoutedEventArgs e)
{
BitmapImage img = (sender as FrameworkElement).Tag as BitmapImage;
// If the image is removed from the bound list the respective visual elements
// will automatically be removed as well.
ImageList.Remove(img);
}
But obj does not contain the name of the image since its a RoutedEventArgs.
True, but the obj at that point is a MenuItem, if you drill one level down, you can get the image.
Is there any way I can get the selected item in the context menu?
Normally one would load the model classes (Image in your case) through the binding of ItemSource of the Menu (or MenuItem if they are to be submenus) and if one takes that route they can pull the originating item off of the DataContext such as in my case the item was an MRU class item.
private void SelectMRU(object sender, RoutedEventArgs e)
{
var mru = (e.OriginalSource as MenuItem).DataContext as MRU;
var name = mru.Name;
...
}
Because you do things by hand you should load the Tag property of the MenuItem with the Image in question
mi1.Tag = {Image instance in question};
then extract on the event.
var image = (e.OriginalSource as MenuItem).Tag as Image;