Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all 18858 articles
Browse latest View live

Get Cursor Postion in Access Text Box using VBA

$
0
0

I want to be able to find the position of the Cursor inside a Text Box control using Access VBA.

What I have in mind is to be able to insert standard text phrases into existing text inside a Text Box, buy first putting an insertion point into the text by clicking in the Text Box Control.  I then intend to have a Combo Box preloaded with standard phrases that can then be inserted at the insertion point in the Test Box, simply by selecting them from the Combo Box.

It's pretty easy to add them at the start of the existing text, but how do I do it somewhere in the middle?


Focusing textbox with IDataErrorInfo?

$
0
0

I have 2 tabitem 

<Grid x:Name="grid" Margin="0,25,0,0"> <TabControl><TabItem x:Name="First"><Grid Background="Black"/></TabItem><TabItem x:Name"Second"><Grid><Label" Content="First Name:" Grid.Column="0" Grid.Row="0" /><Label  Content="Last Name:" Grid.Column="0" Grid.Row="1" /><Label  Content="Age:" Grid.Column="0" Grid.Row="2" /><TextBox x:Name="tbFirstName" Grid.Row="0" Grid.Column="1" Validation.Error="Validation_Error"
                 Text="{Binding UpdateSourceTrigger=PropertyChanged, Path=FirstName,
                        ValidatesOnDataErrors=true, NotifyOnValidationError=true}" /><TextBox x:Name="tbLastName" Grid.Row="1" Grid.Column="1" Validation.Error="Validation_Error"
                 Text="{Binding UpdateSourceTrigger=PropertyChanged, Path=LastName, 
                        ValidatesOnDataErrors=true, NotifyOnValidationError=true}" /><TextBox x:Name="tbAge" Grid.Row="2" Grid.Column="1" Width="50" HorizontalAlignment="left" 
                 Validation.Error="Validation_Error" MaxLength="2"
                 Text="{Binding UpdateSourceTrigger=PropertyChanged,
                 Path=Age, ValidatesOnDataErrors=true, NotifyOnValidationError=true}" /><Button Content="Add" Grid.ColumnSpan="2" Grid.Row="3" Grid.Column="1" Margin="0,0,10,0"
                HorizontalAlignment="right" VerticalAlignment="Center" Command="New"  /></Grid></TabItem></TabControl></Grid>

I got validation on the tabItem 2,but when I click tabitem 1 and go back to tabitem 2 validation is gone.

I want to the validation still show when I click tabitem 1 and go back to tabitem 2

How can I solve this?Thanks

Strange error from event handler in style

$
0
0

Hi there, I am aware that event setters should be used to attach handles in styles. However, can anyone explain this error?

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><Window.Resources><Style TargetType="DataGridCell" x:Key="MenuStyle"><Setter Property="ContextMenu"><Setter.Value><ContextMenu><MenuItem Header="Hello!" Click="MenuItem_Click" /></ContextMenu></Setter.Value></Setter></Style></Window.Resources><Grid> <!-- cast target --><DataGrid><DataGrid.Columns><DataGridTextColumn Header="Column" CellStyle="{StaticResource MenuStyle}" /></DataGrid.Columns></DataGrid></Grid></Window>

where the handler is empty (private void MenuItem_Click(object sender, EventArgs e) {}).

Designer is happy with this. However, at runtime, a XamlParseException is thrown ('Set connectionId threw an exception.' Line number '9' and line position '26'.) with this inner exception: "Unable to cast object of type 'System.Windows.Controls.MenuItem' to type 'System.Windows.Controls.Grid'."

I have observed that it tries to cast MenuItem to whatever parent is there to the DataGrid, or, if not parented, to the DataGrid itself.

I don't quite understand why, or what the intent is. Does anybody have a clue?
(I am trying to understand the cause of the exception, not to fix it.)

Thanks,
Jan


Binding a DataGrid*Column to data in code-behind

$
0
0

I would like to bind a DataGrid*Column (in this particular case, a DataGridTextBox) to its data in the code-behind. This is because, depending on a CheckBox's IsClicked property, the Column needs to bind to different collections.

Solutions such as this one all point to the following sort of code:

var binding =newBinding("X");XColumn.Binding= binding;

Now, I've made use of this sort of code in other parts of my program with success, just not with aDataGrid*Column. With the column, however, this is not working as expected, since in fact all the rows of the column are presenting the X-value of the first element of the collection. This is confirmed when I edit any of the cells and all of them are altered, meaning they are all bound to the same single element of the collection, not to the collection as a whole.

Here is the relevant code:

//This is called whenever the CheckBox EqualToResults is clickedvoidControlBindings(){//only showing for (.IsChecked == true), but the other case is similar//and presents the same problemsif(EqualToResults.IsChecked==true){var cable =DataContextasNCable;var binding =newBinding("X");
        binding.Source= cable.Points;//XColumn is the DataGridTextColumnXColumn.Binding= binding;}}

Should it be relevant, here's the relevant code for the NCable class.

publicclassNCable:DependencyObject,INotifyPropertyChanged{publiceventPropertyChangedEventHandlerPropertyChanged;publicObservableCollection<NPoint>Points;publicstaticDependencyPropertyPointsProperty=DependencyProperty.Register("Points",typeof(ICollectionView),typeof(NCable));publicICollectionViewIPointCollection{
        get {return(ICollectionView)GetValue(PointsProperty);}set{SetValue(PointsProperty, value);}}publicNCable(string cableName){Points=newObservableCollection<NPoint>();for(int i =0; i <11; i++)Points.Add(newNPoint(1,1));IPointCollection=CollectionViewSource.GetDefaultView(Points);}}

TextBox Search (Remove space character)?

$
0
0

I ceated textbox for search

this is ViewModel :

 ICollectionView clv;
 string search = String.Empty;
        public string Search
        {
            get { return search; }
            set
            {
                search = value;
                clv.Filter = FilterData;
                OnPropertyChanged("Search");
            }
        }

        private bool FilterData(object item)
        {
            var value = (datamodels)item;
            if (value == null)
                return false;

            return value.name.Contains(Search, StringComparison.OrdinalIgnoreCase) ||
                   value.address.Contains(Search, StringComparison.OrdinalIgnoreCase);
        }

View

<TextBox  TextWrapping="NoWrap" Text="{Binding Search, UpdateSourceTrigger=PropertyChanged}" Background="#FFEDF1F2"/>

But when I searching words is match case for space character

example: Search : Adam Jordan  then show Adam Jordan in my datagrid (with space character)

                           AdamJordan then no show anything in my datagrid(no Character space)

I want to when I searching AdamJordan or Adam Jordan then show Adam Jordan in my datagrid

How to remove space character in my textbox search?

Thank.

 

When use lisview into scrollview then haven't show data.

$
0
0

<ListView x:Name="lstinfor"  ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
                               <ListView>
                                   <ListView.ItemTemplate>
                                       <DataTemplate>
                                           <StackPanel Width="400">
                                               <TextBlock Text="{Binding info}" Foreground="#666666"></TextBlock>
                                           </StackPanel>
                                       </DataTemplate>
                                   </ListView.ItemTemplate>
                               </ListView>
                            </ScrollViewer>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>

When use lisview into scrollview then haven't show data.

C# problom with facebook sharing article content from my ASP.Net 4.0 WebSite

$
0
0

I have been looking into facebook integration with ASP.Net 4.0 WebSite / WebForms using masterpage. And i have to say that its not so much good exsamples out on google when it comes to using ASP.Net C# for achivieng facebook integration...

We can find many good explanations about facebook OG: type Meta Tags, and how to use them / set up. These links helped me alot to understand the basic of how it works, but still iam not in GOAL yet.

I have manged to dynamically create my FB OG meta tags using HtmlMeta in C#, below u can se the code and the result from html page source.

var hm =newHtmlMeta();
 hm.Attributes.Add("property","og:title");
 hm.Content= meta.ogTitle;
 head.Controls.Add(hm);

This is how it looks like in html page source:

<meta name="viewport" content="width=device-width" /><meta property="og:title" content="NTF i samarbeid med F:E:A:M" /><meta property="og:type" content="article" /><meta property="og:description" content="Alle sender påmelding til Trondheim muay thai. Det vil også være seminarer i andre kampsporter samme dagene. Blant annet med 10 ganger verdensmester 3 ganger i fullkontakt kickboksing. Få med &quot;martial arts weekend&quot; og meld deg på nå." /><meta property="og:image" content="http://mydomain.no/Images/NewsImages/logo1.jpg" /><meta property="og:url" content="http://mydomain.no/NyhetsArtikkel.aspx?ArtikkelId=1" /><meta property="og:site_name" content="NTF" /><meta property="fb:app_id" content="xxxxxxxxxxxxxx" /></head>


And when i test my website in facebook "Open Graph Object Debugger" i get NO error messages saying that i have to fix any thing in my code. At the beginning i had some issues but i managed to fix them.

And in pic below is rest of the debugger report from facebook, as you can se the preview of sharing information is perfect and as i want it to be, looks like every thing with the OG Meta Tags looks fine now since facebook "Open Graph Object Debugger" is not giving any warning or error to fix.

And when i try to share or like a news in my news article page, it dosent show any information from meta tags i have defined...

I have checked every thing many times, and read all article on google about this topic, but i have to say not easy to find any good sample to follow in ASP.NEt C#, and those samples you find are just crap....now iam out of patient and getting mad by this facebook integration problom is bugging me alot.

Exception from HRESULT: 0x800A03EC

$
0
0
Private Sub BtnExportExcel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles BtnExportExcel.Click
        'Using save file dialog that allow you to chosse the file name.
        Dim objDlg As New SaveFileDialog
        objDlg.Filter = "Excel File|*.xls"
        objDlg.OverwritePrompt = False
        If objDlg.ShowDialog = DialogResult.OK Then
            Dim filepath As String = objDlg.FileName
            ExportToExcel(dt, filepath)
        End If
    End Sub
    Private Sub ExportToExcel(ByVal dtTemp As DataTable, ByVal filepath As String)
        Dim strFileName As String = filepath
        If System.IO.File.Exists(strFileName) Then
            If (MessageBox.Show("Do you want to replace from the existing file?", "Export to Excel", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = System.Windows.Forms.DialogResult.Yes) Then
                System.IO.File.Delete(strFileName)
            Else
                Return
            End If

        End If
        Dim _excel As New Excel.Application
        Dim wBook As Excel.Workbook
        Dim wSheet As Excel.Worksheet

        wBook = _excel.Workbooks.Add()
        wSheet = wBook.ActiveSheet()

        Dim dt As System.Data.DataTable = dtTemp
        Dim dc As System.Data.DataColumn
        Dim dr As System.Data.DataRow
        Dim colIndex As Integer = 0
        Dim rowIndex As Integer = 0

        ' export the Columns 
        ' If CheckBox1.Checked Then
        For Each dc In dt.Columns
            colIndex = colIndex + 1
            wSheet.Cells(1, colIndex) = dc.ColumnName
        Next
        ' End If

        'export the rows 
        For Each dr In dt.Rows
            rowIndex = rowIndex + 1
            colIndex = 0
            For Each dc In dt.Columns
                colIndex = colIndex + 1
 wSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)   Its throwing error here.........................................................................................................
            Next
        Next
        wSheet.Columns.AutoFit()
        wBook.SaveAs(strFileName)

        'release the objects
        ReleaseObject(wSheet)
        wBook.Close(False)
        ReleaseObject(wBook)
        _excel.Quit()
        ReleaseObject(_excel)
        ' some time Office application does not quit after automation: so i am calling GC.Collect method.
        GC.Collect()

        MessageBox.Show("File Export Successfully!")
    End Sub
    Private Sub ReleaseObject(ByVal o As Object)
        Try
            While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
            End While
        Catch
        Finally
            o = Nothing
        End Try
    End Sub

Please Help........................................................................


Mayday! WPF Guru urgently required, for love and glory from all the community!

$
0
0

Mayday! Mayday!

A distress signal is being sent out to all past, present and future Gurus!

We need more of your awesomeness!

The TechNet Guru Competitions have become BIG news within Microsoft circles, drawing in more and more departments. Over the last year or so, we have found new and old talent emerging from the community. This is your chance to come out of the shadows of daily grind and take your rightful place in the sun. Come bask in the glory we bestow upon our winners. Build a reputation and promote your own awesomeness to the world (and potential employers).

So bring us your snippets, black holes and revelations. Enlighten us with your factoids and work-arounds. Thrill us with your nifty walk-throughs, overviews and analysis.

Not forgetting Star Wars day!

May the 4th be with you!

All you have to do is add an article to TechNet Wiki from your own specialist field. Something that fits into one of the categories listed on the submissions page. Copy in your own blog posts, a forum solution, a white paper, or just something you had to solve for your own day's work today.

Drop us some nifty knowledge, or superb snippets, and become MICROSOFT TECHNOLOGY GURU OF THE MONTH!

This is an official Microsoft TechNet recognition, where people such as yourselves can truly get noticed!

HOW TO WIN

1) Please copy over your Microsoft technical solutions and revelations toTechNet Wiki.

2) Add a link to it on THIS WIKI COMPETITION PAGE (so we know you've contributed)

3) Every month, we will highlight your contributions, and select a "Guru of the Month" in each technology.

If you win, we will sing your praises in blogs and forums, similar to the weekly contributor awards. Once "on our radar" and making your mark, you will probably be interviewed for your greatness, and maybe eventually even invited into other inner TechNet/MSDN circles!

Winning this award in your favoured technology will help us learn the active members in each community.

Feel free to ask any questions below.

More about TechNet Guru Awards

Thanks in advance!
Pete Laker


#PEJL

Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over to the one and onlyTechNet Wiki, for future generations to benefit from! You'll never get archived again!

If you are a member of any user groups, please make sure you list them in the Microsoft User Groups Portal. Microsoft are trying to help promote your groups, and collating them here is the first step.

WPF application

$
0
0
How to create intellisense to textbox with values from database. Also i need to make a billing application for which as i enter details n textbox it should form a billing type table. could anyone help me on the coding.

How to Select Elements Over the DataTemplete object in Hub Page in XAML

$
0
0
<HubSection x:Name="mainSection" Width="780" Margin="0" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"><DataTemplate><Grid><Grid.RowDefinitions><RowDefinition Height="*" /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="*" /></Grid.ColumnDefinitions><Canvas Grid.Row="1" Background="#343434" x:Name="fullPanel"><Rectangle Fill="Red" Height="400" Width="400" Canvas.Top="{Binding ElementName=mainSection, Path=ActualHeight}" Canvas.Left="{Binding ElementName=fullPanel, Path=ActualWidth}"></Rectangle></Canvas></Grid></DataTemplate></HubSection>

The problem is,, The Rectangle should be showing starting from the bottom-right corner where the Canvas ended, as per the code. But, I'm unable to select the Enclosing "HubSection" element (or any other visual object) outside the DataTemplate object. And besides, binding the size with the enclosing Canvas or the Grid object within the DataTemplete, is not returning me any value other than zero for Height/Width/ActualHeight/ActualWidth.

In some other question, I found an answer, but it is not working for me, because
in "RelativeSource" attribute within "Binding", only 2 options are available - Dispatch, Mode.
Width={Binding RelativeSource={Dispatch="", Mode=""}}

Thanks in Advance for any working solution.

Preview Mouse Left Up mapping to wrong method

$
0
0

I am using c# wpf to write a program. In this program I created multiple canvas' and want to control what happens when I press them individually. For example :

Canvas homeButton = new Canvas();

homeButton.Width = 20;

homeButton.Height = 20;

homeButton.PreviewMouseLeftUp += homeButtonControl;

Canvas backButton = new Canvas();

backButton.Width = 20;

backButton.Height = 20;

backButton.PreviewMouseLeftUp += backButtonControl;

I control them with these methods:

private void homeButtonControl(Object sender, RoutedEventArgs e)

{

//Hide all open canvas'

//display home canvas

}

private void backButtonControl(Object sender, RoutedEventArgs e)

{

//Hide all open canvas'

//display last open canvas which in my case was another canvas called options

}

I have a total of 5 canvas' and both buttons are the top most so that they are always visible. When I press the back button I should see the last canvas viewed, which in the case I am testing is a canvas named Options. However, I see the Home canvas. I set a breakpoint in my backButtonControl method and never got in there when I press my backButton. However, when I put a break point in my homeButtonControl I get in there when I press the backButton.

I want to avoid using a button because I do not want to use the button style. I also do not want to create my own style to overwrite to original. I just want to use and ImageBrush for the background as textures for my "buttons."

So why when I press the backButton does it map to the incorrect method call?

Any help would be greatly appreciated.

Matt

WPF application

$
0
0
how to add edit and delete options to a datagrid

WPF application

$
0
0
how to change the tab control to enter control in moving from one field to another. and also if a value is entered how to automatically shift to the next field.

EKAMBARAM B

Must disconnect specified child from current parent Visual before attaching to new parent Visual.

$
0
0
If I use the date picker control to display its calendar, then change themes, and then go back and try to use the calendar from the date picker once again, I am getting the following error

"Must disconnect specified child from current parent Visual before attaching to new parent Visual."

Please help me if anyone faced the same issue.


WPF application

$
0
0
how to change the tab control to enter in moving from one field to another. and how to set auto increment values to a textbox.

EKAMBARAM B

WPF application

$
0
0
there is an exception handled when i use more then one combo box and connect each combo box to sql . could you help me out.

EKAMBARAM B

How to show pop up in a listview when an item is selected?

$
0
0

Hi, I have a listview which shows displays thumbnails, The thumbnail size is 150 x 150 pixels, I have two data templates when , one with a highlighted border to show the selected item and one with no highlighting. What i want is when the item is selected, i want to show a user control inside a pop up on top of the selected item with an offset of 10 pixels vertically. The listview has multiple selection so when the user selects multiple items i want the pop up location to be updated. Can anybody tell me on how to do this? Please see the code below, when i do the following the pop up sometimes moves to the bottom left or bottom right of the screen.I have a method shoesheetlistmenu() which i am calling when the user clicks on the thuumbnail, I have handled previewmousedown and inside that event i am calling showsheetlistmenu(). But this does not give me the selected item correctly. Is there any other way to do this? Can ido the same thing in xaml without any code behind?.Any help is much appreciated. 

       private void ShowSheetListMenu()
        {
            if (null == sheetListContextMenu)
            {
                sheetListContextMenu = new SheetListContextMenu();
                sheetListPopup = new Popup
                {
                    Child = sheetListContextMenu,
                    Placement = PlacementMode.Top,
                };
                this.RootGrid.Children.Add(sheetListPopup);
            }

            //Show the pop up only when the sheet is open. Else do not show it.
            if (null != sheetListPopup && sheetListPopup.IsOpen)
            {
                sheetListPopup.IsOpen = false;
            }
            if (IsSheetListOpen)
            {
                if (IsSheetListFullScreen)
                    sheetListContextMenu.ShowMultiRowContextMenu();
                else
                    sheetListContextMenu.ShowSingleRowContextMenu();

                //Checking whether the selected item is a thumbnail, If it is a thumbnail only then show the pop up
                if (NoteThumbnailList.SelectedItems.Count > 0 && NoteThumbnailList.SelectedItems.OfType<ThumbnailData>().Count() > 0 && false == displayPopUp)
                {
                    UIElement selectedContainer =
                            NoteThumbnailList.ItemContainerGenerator.ContainerFromIndex(NoteThumbnailList.SelectedIndex) as UIElement;
                    sheetListPopup.PlacementTarget = selectedContainer;
                    sheetListPopup.Placement = PlacementMode.Top;
                    sheetListPopup.HorizontalOffset = 0;
                    sheetListPopup.VerticalOffset = -20;
                    sheetListPopup.IsOpen = true;
                }
            }
        }


Thanks and Regards, JohnnyWalker.

Drawing a grid on canvas and Binding!

$
0
0

Hi,

I have to draw a grid on the canvas and also bind the grid box size to a property as the size of the grid box can be varied with a slider control.

So far I did this:

<Canvas><Canvas.Background><VisualBrush TileMode="Tile"
            Viewport="0,0,10,10" ViewportUnits="Absolute" 
            Viewbox="0,0,10,10" ViewboxUnits="Absolute"><VisualBrush.Visual><Rectangle Stroke="Darkgray" StrokeThickness="0.5" Height="10" Width="10"
                StrokeDashArray="0.5"/></VisualBrush.Visual></VisualBrush></Canvas.Background></Canvas>

and this gives me a nice grid.

But I don't know how to change this (viewport and viewbox) with a slider. How can I bind this with slider control or is there any other way to draw a grid than what I have done?

Would appreciate any help :)


Please Mark as Answered If this answers your question OrUnMark as Answered if it did not.
Happy to Help :)
My Site

Canvas save final image with child image

$
0
0

I want to place a thumbnail image on an existing Image and let the user to place the thumbnail any where on the existing Image & finally save the Image.

I have the existing image inside the canvas & placed the thumbnail added over the canvas.  
But the problem is that the thumbnail is moving any where on the grid & I couldn't remove my cursor from the generated thumbnail image & I couldn't save both the image.

How can I let the user to move/drag the thumbnail image within the original Image and save the final Image? Thank you

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib"
         x:Class="ImagePrintUtility.SpecialEffects"
        Title="SpecialEffects" Height="768" Width="1024" WindowStyle="None" 
    WindowStartupLocation="CenterScreen"  BorderBrush="Brown" BorderThickness="2" ><Grid Background="AliceBlue"><Grid.ColumnDefinitions><ColumnDefinition Width="100" /><ColumnDefinition Width="*" /><ColumnDefinition Width="100"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="70"/><RowDefinition  Height="*"/></Grid.RowDefinitions><Border Grid.Column="0" ><Image Name="imgPic1" Source="logo.jpg"    Stretch="Fill" VerticalAlignment="Stretch" /></Border><DockPanel  Grid.Column="1" x:Name="dDock" Background="AliceBlue"><WrapPanel MinWidth="605" HorizontalAlignment="Stretch" VerticalAlignment="Top"><Button Content="AddLogo" Click="Button_Click" Margin="5" Grid.Column="1"  Height="32" Width="90" /><Button Content="Reset Logo" x:Name="bresetLogo" Height="32" Width="90" Margin="5"  Grid.Column="1"/></WrapPanel></DockPanel>><WrapPanel Grid.Column="2" Background="AliceBlue"><Button  Name="bSave" Width="90" Margin="5,1"  Height="32"  Content="Save" Click="bSave_Click" /><Button x:Name="btnClose" Content="Close" Height="32" Width="90" Margin="5,3"  Click="btnClose_Click"    /></WrapPanel><Canvas x:Name="canvas"    HorizontalAlignment="Stretch"  Grid.Column="1" Grid.Row="1" 
            MouseLeftButtonDown="CanvasMouseLeftButtonDown"
            MouseLeftButtonUp="CanvasMouseLeftButtonUp"
            MouseMove="CanvasMouseMove" Margin="0,0,31,0"><Image x:Name="SpecialPhoto"    Source="IMG_0071.JPG" Height="586" Width="780"
				Stretch="Uniform" VerticalAlignment="Top" HorizontalAlignment="Center" /></Canvas></Grid></Window>

.Cs

 public partial class SpecialEffects : Window
    {
        private string FileNmae;
        public SpecialEffects(string getTheFN) //Load the selected Image from ParentWindow
        {
            InitializeComponent();
             FileNmae = getTheFN;

            BitmapImage src = new BitmapImage();
            src.BeginInit();
            src.UriSource = new Uri(FileNmae, UriKind.Relative);
            src.CacheOption = BitmapCacheOption.OnLoad;
            src.EndInit();
            SpecialPhoto.Source = src;
            
        }

        private Image draggedImage;
        private Point mousePosition;

        private void CanvasMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var image = e.Source as Image;

            if (image != null && canvas.CaptureMouse())
            {
                mousePosition = e.GetPosition(canvas);
                draggedImage = image;
                Panel.SetZIndex(draggedImage, 1); // in case of multiple images
            }
        }

        private void CanvasMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (draggedImage != null)
            {
                canvas.ReleaseMouseCapture();
                Panel.SetZIndex(draggedImage, 0);
                draggedImage = null;
            }
        }

        private void CanvasMouseMove(object sender, MouseEventArgs e)
        {
            if (draggedImage != null)
            {
                var position = e.GetPosition(canvas);
                var offset = position - mousePosition;
                mousePosition = position;
                Canvas.SetLeft(draggedImage, Canvas.GetLeft(draggedImage) + offset.X);
                Canvas.SetTop(draggedImage, Canvas.GetTop(draggedImage) + offset.Y);
            }
        }
 private void Button_Click(object sender, RoutedEventArgs e) // To load another image
        {
            var dialog = new Microsoft.Win32.OpenFileDialog();
            dialog.Filter ="Image Files (*.jpg;*.png; *.jpeg; *.gif; *.bmp)|*.jpg;*.png; *.jpeg; *.gif; *.bmp";

            if ((bool)dialog.ShowDialog())
            {
                BitmapImage src = new BitmapImage();
                src.BeginInit();
                src.UriSource = new Uri(dialog.FileName, UriKind.Relative);
                src.DecodePixelHeight = 100;
                src.DecodePixelWidth = 100;
                src.CacheOption = BitmapCacheOption.OnLoad;
                src.EndInit();

                var image = new Image { Source = src };
                Canvas.SetLeft(image, 0);
                Canvas.SetTop(image, 0);
                canvas.Children.Add(image);
            }
        }
        
        private void bSave_Click(object sender, RoutedEventArgs e) // To Save the final image with the loaded image
        {
            string fileLocation = System.IO.Path.GetDirectoryName(FileNmae);// get the selected file location
            string getFileName = System.IO.Path.GetFileName(FileNmae); //get the seleceted filename
            //StringBuilder finalFileName = new StringBuilder(getFileName);
            //finalFileName.Insert(0, "$"); // produces "Help"
            DateTime time = DateTime.Now;              // Use current time
            string format = "MMMddddHHmmssyyyy";
            string s2 = time.ToString(format) + getFileName; // add $ at front along with the folde name


            string filenamecombined = System.IO.Path.Combine(fileLocation, s2);//combine path. 

            //ViewedPhoto is the Image element

            RenderTargetBitmap renderTarget = new RenderTargetBitmap(
             (int)SpecialPhoto.ActualWidth,
             (int)SpecialPhoto.ActualHeight,
             96, 96, PixelFormats.Pbgra32);

            //renderTarget.Render(ViewedPhoto);
            ModifyPosition(SpecialPhoto as FrameworkElement);
            renderTarget.Render(SpecialPhoto);
            ModifyPositionBack(SpecialPhoto as FrameworkElement);

            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(renderTarget));

            //string imagePath = System.IO.Path.GetTempFileName();
            using (FileStream stream = new FileStream(filenamecombined, FileMode.Create))
            {
                encoder.Save(stream);
                stream.Dispose();
            }
        }
        private void ModifyPosition(FrameworkElement fe)
        {
            /// get the size of the visual with margin
            System.Windows.Size fs = new System.Windows.Size(
                fe.ActualWidth +
                fe.Margin.Left + fe.Margin.Right,
                fe.ActualHeight +
                fe.Margin.Top + fe.Margin.Bottom);

            /// measure the visual with new size
            fe.Measure(fs);

            /// arrange the visual to align parent with (0,0)
            fe.Arrange(new Rect(
                -fe.Margin.Left, -fe.Margin.Top,
                fs.Width, fs.Height));
        }

        private void ModifyPositionBack(FrameworkElement fe)
        {
            /// remeasure a size smaller than need, wpf will
            /// rearrange it to the original position
            fe.Measure(new System.Windows.Size());
        }

        
    }

Viewing all 18858 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>