Copy wpf imageSource to another wpf imageSource - c#

I want to copy imageSource to another imageSource. When A window contains image is closed, then I want to make image in A will be copied to B window image and then open B window.
I tried to test with below code. but it wasn`t work.
ADDED :
I upload more code about relevant image code. but im sorry that i cant upload full source code but If you ask, I will edit the related source and upload it.
A a = new A();
B b;
a.Closing += delegate {
b = new B();
b.img.Source = a.img.Source;
b.Show();
};
a.Show();
<!-- a.img xml -->
<Grid x:Name="ImageGrid" Margin="0,36,10,10">
<Grid.LayoutTransform>
<TransformGroup>
<ScaleTransform x:Name="ScaleTransform"
ScaleX="{Binding ZoomRate}" ScaleY="{Binding ZoomRate}"/>
<RotateTransform/>
</TransformGroup>
</Grid.LayoutTransform>
<Image Name="img" HorizontalAlignment="Left" VerticalAlignment="Top"
Source="{Binding BitmapSource, Mode=TwoWay}"/>
<Canvas HorizontalAlignment="Left" VerticalAlignment="Top"
Name="canvas2"
Background="Transparent"
Width="{Binding Path=ActualWidth, ElementName=imgBefore2}"
Height="{Binding Path=ActualHeight, ElementName=imgBefore2}"
MouseLeftButtonDown="Canvas2_MouseLeftButtonDown"
MouseMove="Canvas2_MouseMove"
MouseLeftButtonUp="Canvas2_MouseLeftButtonUp"
MouseRightButtonDown="Canvas2_MouseRightButtonDown">
</Canvas>
</Grid>
<!-- b.img xml -->
<Grid x:Name="ImageGrid"
Background="Transparent"
Width="{Binding MaxWidth, ElementName=ScrollViewer}"
Height="{Binding MaxHeight, ElementName=ScrollViewer}"
MouseMove="Canvas_MouseMove"
MouseLeftButtonDown="Canvas_MouseLeftButtonDown"
MouseLeftButtonUp="Canvas_MouseLeftButtonUp"
MouseWheel="Canvas_MouseWheel">
<Grid.LayoutTransform>
<TransformGroup>
<ScaleTransform x:Name="ScaleTransform" ScaleX="{Binding ZoomRate}" ScaleY="{Binding ZoomRate}"/>
<RotateTransform/>
</TransformGroup>
</Grid.LayoutTransform>
<Image x:Name="img" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Canvas HorizontalAlignment="Left" VerticalAlignment="Top"
x:Name="canvas"
Background="Transparent"
Width="{Binding ActualWidth, ElementName=imgBefore}"
Height="{Binding ActualHeight, ElementName=imgBefore}"/>
</Grid>
public Mat src;
public BitmapSource BitmapSource {
get
{
return bitmapSource;
}
set
{
bitmapSource = value;
OnPropertyChanged("bitmapSource");
} // ViewModel Code
}
private void LoadImage(System.Drawing.Bitmap bm)
{
src = OpenCvSharp.Extensions.BitmapConverter.ToMat(bm);
OriginWidth = src.Width;
OriginHeight = src.Height;
BitmapSource = OpenCvSharp.Extensions.BitmapSourceConverter.ToBitmapSource(src);
} // Load Image for a.img

Related

How to align combobox popup to bottom Left wpf?

Goal: To align combobox popup to bottom Left. Kindly check image below for reference:
What i tried?: I tried playing with Placement property of PART_Popup. If i set Placement="Bottom", the Popup is rendering from Bottom right. Check this image below:
Also, in VS Designer it is showing correctly:
ComboBox PART_Popup:
<Popup x:Name="PART_Popup"
AllowsTransparency="true" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Margin="1" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom"
MinWidth="170">
<themes:SystemDropShadowChrome x:Name="shadow" Color="Transparent" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{Binding ActualWidth, ElementName=templateRoot}">
<Border x:Name="dropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="1" Background="{StaticResource ComboBox.Static.Background}"
CornerRadius="3">
<ScrollViewer x:Name="DropDownScrollViewer" CanContentScroll="False">
<Grid x:Name="grid" RenderOptions.ClearTypeHint="Enabled">
<Canvas x:Name="canvas" HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
<Rectangle x:Name="opaqueRect" Fill="{Binding Background, ElementName=dropDownBorder}"
Height="{Binding ActualHeight, ElementName=dropDownBorder}" Width="{Binding ActualWidth, ElementName=dropDownBorder}"/>
</Canvas>
<ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Margin="16"/>
</Grid>
</ScrollViewer>
</Border>
</themes:SystemDropShadowChrome>
</Popup>
XAML:
<ComboBox
HorizontalAlignment="Left"
VerticalAlignment="Center"
SelectedIndex="0"
Margin="50,0"
Style="{StaticResource FlatComboBoxStyle2}">
<ComboBoxItem Content="Recent"/>
<ComboBoxItem Content="Alphabetical"/>
</ComboBox>
I am looking for XAML code solution only. Thanks.
I fixed it by adding a converter in App.xaml.cs:
public class PositiveToNegativeConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double) value > 0 ? 0 - (double) value : 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
And define it in my ComboBoxTemplate:
<PositiveToNegativeConverter x:Key="PositiveToNegativeConverter" />
And call it like this in Popup's HorizontalOffest:
HorizontalOffset="{Binding ActualWidth, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource PositiveToNegativeConverter}}"
I hope this helps out anyone looking for solution.
I had the same issue, and after following several thread here (all my XAML trial failed, to brief up, Popup.Placement = [whatever] didn't change anything on run) I ended up with the following "solution".
Not pretty, so if you knew more elegant way I'm open.
So I named my ComboBox and Add a event handler (via XAML) on DropDownOpen (this is the dirty side imo) where I force my Popup.Placement to RelativePoint and set a VerticalOffset to my ComboBox.ActualHeight.
Here is the XAML code :
<ComboBox Name="NIC_CmbBox" HorizontalAlignment="Stretch" DropDownOpened="NIC_CmbBox_DropDownOpened">
C# :
private Popup _comboBoxPopup;
private void NIC_CmbBox_DropDownOpened(object sender, EventArgs e)
{
ComboPopupPlacement();
}
public Popup ComboBoxPopup {
get
{
if(_comboBoxPopup == null)
{
//try to get it
if(NIC_CmbBox != null)
_comboBoxPopup = (Popup)NIC_CmbBox.Template.FindName("PART_Popup", NIC_CmbBox);
}
return _comboBoxPopup;
}
set => _comboBoxPopup = value; }
public void ComboPopupPlacement()
{
//If placement haven't already be done
if (ComboBoxPopup != null && _comboBoxPopup.Placement != PlacementMode.RelativePoint)
{
_comboBoxPopup.Placement = PlacementMode.RelativePoint;
_comboBoxPopup.VerticalOffset = NIC_CmbBox.ActualHeight;
}
}

Elements loaded via XamlReader() and from MainWindow.Xaml behave differently?

I have the following Viewbox in MainWindow.Xaml:
<Viewbox x:Name="R1C1Viewbox" Grid.Row="1" Grid.Column="2"
Grid.ColumnSpan="1" Grid.RowSpan="1">
<Border x:Name="R1C1Border" BorderBrush="White" CornerRadius="3"
BorderThickness="2" Background="White"
Height="40" Width="40" Margin="0,3,3,0">
<Grid x:Name="R1C1Grid">
<TextBlock x:Name="R1C1TextBlock1" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Arial" FontWeight="Bold" Text="+" FontSize="22"></TextBlock>
<Polygon x:Name="R1C1LED"
Points="0,0 15,0 0,15"
Stroke="#FFED1C24"
StrokeThickness="1">
<Polygon.Fill>
<RadialGradientBrush>
<GradientStop Color="White" Offset="2.5"/>
<GradientStop Color="Black"/>
</RadialGradientBrush>
</Polygon.Fill>
</Polygon>
<Button x:Name="R1C1Button" Background="Transparent"
BorderBrush="Transparent">
</Button>
</Grid>
</Border>
</Viewbox>
In my code behind, I define 2 RadialGradientBrushes for the Polygon.Fill property:
public static RadialGradientBrush ledOn = new RadialGradientBrush();
public static RadialGradientBrush ledOff = new RadialGradientBrush();
ledOn.GradientStops.Add(new GradientStop(Colors.Red, .8));
ledOn.GradientStops.Add(new GradientStop(Colors.White, 0));
ledOff.GradientStops.Add(new GradientStop(Colors.White, 2.5));
ledOff.GradientStops.Add(new GradientStop(Colors.Black, 0));
If I load the viewbox only from MainWindow.xaml, I can use:
R1C1LED.Fill = ledOn;
or
R1C1LED.Fill = ledOff;
and the fill changes as expected. If I load the exact same xaml from a file using XamlReader(), the Viewbox displays exactly as expected but using the code behind to change the fill as above doesn't change the fill and no errors are generated.
Example code:
private void OnTest(object sender, RoutedEventArgs e)
{
var xaml =
#"<Window
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
Title='WPF App' Height='450' Width='800'>
<StackPanel Orientation='Vertical'>
<Button x:Name='R1C1LED' Content='Load Data' />
</StackPanel>
</Window>";
var win = (Window)XamlReader.Parse(xaml);
var button = (Button)win.FindName("R1C1LED");
button.Background = Brushes.Red;
button.Click += (obj, args) => { MessageBox.Show("Hi!"); };
win.Show();
}

Zoom of image with scrollviewer in WPF

I have an Image viewer implemented using ScrollViewer
.XAML
<ScrollViewer Name="viewImg" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" >
<Image Name="bigImage"
Source="/JoyOs.Media;component/img/Plugins/Photos/PHOTO.png"
PreviewMouseLeftButtonUp="ImageMouseLeftButtonUp"
PreviewMouseLeftButtonDown="ImageMouseLeftButtonDown"
PreviewMouseMove="ImageMouseMove" Stretch="Uniform"></Image>
</ScrollViewer>
ScrollViewer class .cs file
public partial class ImageList
{
private void ImageMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var img = (Image)sender;
img.ReleaseMouseCapture();
}
private void ImageMouseMove(object sender, MouseEventArgs e)
{
var img = (Image)sender;
if (!img.IsMouseCaptured) return;
Vector v = _startImgMove - e.GetPosition(viewImg);
viewImg.ScrollToHorizontalOffset(_originImgMove.X - v.X);
viewImg.ScrollToVerticalOffset(_originImgMove.Y - v.Y);
}
private void ImageMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var img = (Image)sender;
img.CaptureMouse();
_startImgMove = e.GetPosition(viewImg);
_originImgMove = new Point(viewImg.HorizontalOffset, viewImg.VerticalOffset);
}
}
I want zoom features implemented in it.Hence I tried to use ZoomBorder.cs class from this.
How to use ZoomBorder.cswith ScrollViewer ?
I tried Without ScrollViewer with only ZoomBorder.cs like this.
<local:ZoomBorder x:Name="border" ClipToBounds="True" Background="Gray">
<Image Name="bigImage"
Source="/JoyOs.Media;component/img/Plugins/Photos/PHOTO.png"
PreviewMouseLeftButtonUp="ImageMouseLeftButtonUp"
PreviewMouseLeftButtonDown="ImageMouseLeftButtonDown"
PreviewMouseMove="ImageMouseMove" Stretch="Uniform"></Image>
</local:ZoomBorder>
I can't answer the question for ZoomBorder's, but I have implemented zoom functionality myself in a different way. I have a ViewBox, which I bind the ScaleTransform of to a value in my ViewModel. Changing the value in my ViewModel then causes the contents of the ViewBox to zoom in and out depending on the value.
<Viewbox x:Name="vwbxZoom" Stretch="None">
<Viewbox.LayoutTransform>
<ScaleTransform ScaleX="{Binding ZoomLevel.Value}"
ScaleY="{Binding ZoomLevel.Value}" />
</Viewbox.LayoutTransform>
</ViewBox>
Here is a quick example. You may use any control as content of the Viewbox
<DockPanel>
<Slider x:Name="ZoomSlider" DockPanel.Dock="Bottom" Minimum="0.05" Maximum="2">
</Slider>
<ScrollViewer HorizontalScrollBarVisibility="Auto">
<Viewbox Stretch="Uniform" VerticalAlignment="Center" HorizontalAlignment="Center">
<Border Width="2000" Height="2000">
<Border.Background>
<LinearGradientBrush StartPoint="0, 0.5" EndPoint="1, 0.5">
<GradientStop Color="Red" Offset="0.33"/>
<GradientStop Color="Green" Offset="0.66"/>
<GradientStop Color="Blue" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
</Border>
<Viewbox.LayoutTransform>
<ScaleTransform ScaleX="{Binding ElementName=ZoomSlider, Path=Value}" ScaleY="{Binding ElementName=ZoomSlider, Path=Value}"/>
</Viewbox.LayoutTransform>
</Viewbox>
</ScrollViewer>
</DockPanel>

Display images in ListBox

I know there are a lot of question like this in the web, but believe me I spent on this a lot of hours and I still not success, I really will glad for any help!
I loading various images in run time and I want to show them in list box (small images, then the user should click on one of them and show him in real size).
my code is:
public partial class MainWindow : Window
{
int imageNumber = 0;
public List<String> ImagePath = new List<String>();
public MainWindow()
{
InitializeComponent();
lb_Images.ItemsSource = ImagePath;
}
private void bu_addImage_Click(object sender, RoutedEventArgs e)
{
addImageToListBox();
}
private void addImageToListBox()
{
imageNumber++;
if (imageNumber == 4) imageNumber = 0;
string directoryPath = AppDomain.CurrentDomain.BaseDirectory;
// load input image
string ImageFilename = directoryPath + "img";
ImageFilename += imageNumber.ToString();
ImageFilename += ".jpg";
ImagePath.Add(ImageFilename);
}
}
and the xaml is:
<Window x:Class="forQuestionWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="216" Width="519">
<Window.Resources>
<DataTemplate x:Key="ImageGalleryDataTemplate">
<Grid>
<Border BorderBrush="#FFFF9800" BorderThickness="1" Width="120" Height="120" Padding="5" Margin="5" CornerRadius="6">
<!--Bind Image Path in Image Control-->
<Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center">
<!--View Large Image on Image Control Tooltip-->
<Image.ToolTip>
<Grid>
<Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center" Height="200" Width="200"></Image>
</Grid>
</Image.ToolTip>
</Image>
</Border>
</Grid>
</DataTemplate>
<ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
<!--Display Images on UniformGrid Panel-->
<UniformGrid Rows="1" Columns="25" HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
</ItemsPanelTemplate>
</Window.Resources>
<Grid>
<Canvas Height="177" HorizontalAlignment="Left" Name="canvas1" VerticalAlignment="Top" Width="497">
<ListBox Canvas.Left="6" Canvas.Top="5" Height="166" Name="lb_Images" Width="441"
BorderBrush="{x:Null}" DataContext="{Binding Source={StaticResource ImageGalleryDataTemplate}}"
ItemsSource="{Binding Source={StaticResource ImageGalleryItemsPanelTemplate}}">
</ListBox>
<Button Canvas.Left="453" Canvas.Top="26" Content="Add" Height="64" Name="bu_addImage" Width="38" Click="bu_addImage_Click" />
</Canvas>
</Grid>
</Window>
I know that the list box updated when I add image path to the list because if I debug I found some items under lb_Images.items, but I show nothing.
I'll glad for any help! thank you!!
Some notes
DataContext for ListBox it's not necessary, then you set ItemSource. Instead of set the ItemTemplate
In DataTemplate remove the {Binding ImagePath}, instead of write {Binding}, because in this case the elements of the DataTemplate inherit DataContext.
When you add new items to ListBox.Items, you must call ListBox.Items.Refresh() or use the ObservableCollection<T>, because:
ObservableCollection represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
Try this example:
XAML
<Window.Resources>
<DataTemplate x:Key="ImageGalleryDataTemplate">
<Grid>
<Border BorderBrush="#FFFF9800" BorderThickness="1" Width="120" Height="120" Padding="5" Margin="5" CornerRadius="6">
<Image Source="{Binding}" Stretch="Fill" HorizontalAlignment="Center">
<Image.ToolTip>
<Grid>
<Image Source="{Binding}" Stretch="Fill" HorizontalAlignment="Center" Height="200" Width="200" />
</Grid>
</Image.ToolTip>
</Image>
</Border>
</Grid>
</DataTemplate>
<ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
<UniformGrid Rows="1" Columns="25" HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
</ItemsPanelTemplate>
</Window.Resources>
<Grid>
<Canvas Height="177" HorizontalAlignment="Left" Name="canvas1" VerticalAlignment="Top" Width="497">
<ListBox Canvas.Left="6" Canvas.Top="5" Height="166" Name="lb_Images" Width="441"
ItemTemplate="{StaticResource ImageGalleryDataTemplate}"
ItemsSource="{Binding Path=ImagePath}">
</ListBox>
<Button Canvas.Left="453" Canvas.Top="26" Content="Add" Height="64" Name="bu_addImage" Width="38" Click="bu_addImage_Click" />
</Canvas>
</Grid>
Code-behind
public partial class MainWindow : Window
{
int imageNumber = 0;
public List<String> ImagePath = new List<String>();
public MainWindow()
{
InitializeComponent();
lb_Images.ItemsSource = ImagePath;
}
private void bu_addImage_Click(object sender, RoutedEventArgs e)
{
addImageToListBox();
}
private void addImageToListBox()
{
imageNumber++;
if (imageNumber == 4) imageNumber = 0;
string directoryPath = AppDomain.CurrentDomain.BaseDirectory;
// load input image
string ImageFilename = directoryPath + "img";
ImageFilename += imageNumber.ToString();
ImageFilename += ".jpg";
ImagePath.Add(ImageFilename);
lb_Images.Items.Refresh();
}
}

how to add a spinner in windows phone 7 app

I have a page in my app where the data comes from the web service. The code is:
public about()
{
InitializeComponent();
KejriwalService.aapSoapClient myclient = new KejriwalService.aapSoapClient();
myclient.getarvindAboutCompleted += new EventHandler<KejriwalService.getarvindAboutCompletedEventArgs>(myclient_getarvindAboutCompleted);
myclient.getarvindAboutAsync();
}
void myclient_getarvindAboutCompleted(object sender, KejriwalService.getarvindAboutCompletedEventArgs e)
{
var data = e.Result;
XElement xml = XElement.Parse(data);
aboutview.Text = xml.Elements("UserDetails").Elements("about_details").First().Value;
}
As the data comes from the web i want to add a spinner which runs till the data comes. Can anyone please help me how to do this for this particular page.
My xaml file is:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,12,12,0">
<Button Click="Image_Phone" BorderThickness="0" Margin="197,155,0,518" HorizontalAlignment="Left" Width="93">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="Image/phone.png"/>
</Button.Background>
</Button>
<Button x:Name="Email" BorderThickness="0" Click="Image_Email" Margin="277,155,85,518">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="Image/email.png"/>
</Button.Background>
</Button>
<Button x:Name="Home" BorderThickness="0" Click="Image_Home" Margin="0,155,-12,518" HorizontalAlignment="Right" Width="102">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="Image/Home-icon.png"/>
</Button.Background>
</Button>
<Button x:Name="previous" BorderThickness="0" Click="Image_Back" Margin="0,0,354,673" HorizontalAlignment="Right" Width="102">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="Image/Previous.png"/>
</Button.Background>
</Button>
<ScrollViewer Margin="0,256,0,6" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Auto" AllowDrop="False" ManipulationMode="Control">
<TextBlock HorizontalAlignment="Left" Name="aboutview" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="439" FontSize="18" FontStyle="Normal" FontWeight="ExtraBlack" Foreground="Black"/>
</ScrollViewer>
<Image Height="172" HorizontalAlignment="Left" Margin="24,78,0,0" Name="image1" Source="Image/icon.png" Stretch="Fill" VerticalAlignment="Top" Width="155" />
<TextBlock Height="34" HorizontalAlignment="Left" Margin="196,78,0,0" Name="textBlock1" Text="Contact No:" VerticalAlignment="Top" Width="147" FontSize="24" Foreground="Black" FontWeight="Bold"/>
<TextBlock Height="36" HorizontalAlignment="Left" Margin="197,118,0,0" Name="textBlock2" Text="+91-9718500606" VerticalAlignment="Top" Width="191" FontSize="24" Foreground="Black" FontWeight="Bold" />
</Grid>
</Grid>
I'd recommend you ProgressBar (or better PerformanceProgressBar from the WP toolkit), if they are matching your requirements. You can add this snippet somewhere inside of ContentPanel Grid:
<ProgressBar Name="progressName"
IsIndeterminate="True"
Visibility="Collapsed"/>
And your code behind should look like this:
public about()
{
InitializeComponent();
KejriwalService.aapSoapClient myclient = new KejriwalService.aapSoapClient();
myclient.getarvindAboutCompleted += new EventHandler<KejriwalService.getarvindAboutCompletedEventArgs>(myclient_getarvindAboutCompleted);
myclient.getarvindAboutAsync();
progressName.Visibility = System.Windows.Visibility.Visible;
}
void myclient_getarvindAboutCompleted(object sender, KejriwalService.getarvindAboutCompletedEventArgs e)
{
var data = e.Result;
XElement xml = XElement.Parse(data);
aboutview.Text = xml.Elements("UserDetails").Elements("about_details").First().Value;
progressName.Visibility = System.Windows.Visibility.Collapsed;
}

Categories