Archive

Posts Tagged ‘WPF’

WPF POPUP control with Drag and Drop support and Resize support

May 27, 2014 Leave a comment

To enable DragDrop support follow the steps

Add namespace System.Windows.Interactivity; in WPF project

Creates a class like this

public class MouseDragPopupBehavior : Behavior<Popup>
    {
        private bool mouseDown;
        private Point oldMousePosition;

        protected override void OnAttached()
        {
            AssociatedObject.MouseLeftButtonDown += (s, e) =>
            {
                mouseDown = true;
                oldMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
                AssociatedObject.Child.CaptureMouse();
            };
            AssociatedObject.MouseMove += (s, e) =>
            {
                if (!mouseDown) return;
                var newMousePosition = AssociatedObject.PointToScreen(e.GetPosition(AssociatedObject));
                var offset = newMousePosition – oldMousePosition;
                oldMousePosition = newMousePosition;
                AssociatedObject.HorizontalOffset += offset.X;
                AssociatedObject.VerticalOffset += offset.Y;
            };
            AssociatedObject.MouseLeftButtonUp += (s, e) =>
            {
                mouseDown = false;
                AssociatedObject.Child.ReleaseMouseCapture();
            };
        }
    }

IN Xaml redesign popup like this

 xmlns:myControl=”clr-namespace:use ur name space”
xmlns:i=”http://schemas.microsoft.com/expression/2010/interactivity&#8221;

 

And design popup like

   <Popup………………….>
                <i:Interaction.Behaviors>
                    <myControl:MouseDragPopupBehavior/>
                </i:Interaction.Behaviors>   
                    …..  Fil popup contents here….     
            </Popup>

To support resize  we need to add few more things .

First redesign popup like

<Popup   Name=”popupname” …>
                <i:Interaction.Behaviors>
                    <myControl:MouseDragPopupBehavior/>
                </i:Interaction.Behaviors>
                <Grid>
                    —-popup contents—
                    <Thumb HorizontalAlignment=”Right” VerticalAlignment=”Bottom” Width=”16″ Height=”16″
                              DragStarted=”onDragStarted” DragDelta=”onDragDelta” DragCompleted=”onDragCompleted”/>
                </Grid>
            </Popup>

 

And in c# write events

  private void onDragStarted(object sender, DragStartedEventArgs e)
        {
            Thumb t = (Thumb)sender;
            t.Cursor = Cursors.Hand;
        }

        private void onDragDelta(object sender, DragDeltaEventArgs e)
        {

            double yadjust = this.popupname.Height + e.VerticalChange;
            double xadjust = this.popupname.Width + e.HorizontalChange;
            if ((xadjust >= 0) && (yadjust >= 0))
            {
                this.popupname.Width = xadjust;
                this.popupname.Height = yadjust;
            }
        }

        private void onDragCompleted(object sender, DragCompletedEventArgs e)
        {
            Thumb t = (Thumb)sender;
            t.Cursor = null;
        }

Advertisements
Categories: Prsnl References Tags:

Customization on WPF ListView

June 5, 2013 2 comments

If  some one is planning to simply bind a list of datas to a listview in WPF its pretty easy and straight forward. But today i came through a case where i need a listbox that supports Sorting , Inline Editting and Save the chages to Db once i finish the inline edit .

I started one by one  1. Sorting and Inline Editting  > Using the logic or idea from this blog http://tech.pro/tutorial/857/wpf-tutorial-using-the-listview-part-3-in-place-edit

2. Saving the changes after finish the edit operation to Db – Add a new event to the textbox where you want to edit the data and do actions on that event

LostFocus=”textWordDescription_LostFocus” Tag=”{Binding}”

             string newtext = ((TextBox)sender).Text;
BindedObject selected = ((TextBox)sender).Tag as BindedObject;
updateDetails(selected.Id,selected);

Then next challenge is  want to sort my datas in ascending order . The following code solves that issue

  private void Sort(string sortBy, ListSortDirection direction)
{
ICollectionView dataView =
CollectionViewSource.GetDefaultView(wordBankListView.ItemsSource);
dataView.SortDescriptions.Clear();
SortDescription sd = new SortDescription(sortBy, direction);
dataView.SortDescriptions.Add(sd);
dataView.Refresh();
}

Next Challenge is with selection . By default i want to select an item in listbox (Its  pretty easy thing . just set selectedvalue ). But i need to handle the position of scrollviewer as well . If 100 items in listbox and i selected an item starts with letter z then thae item is in bottom of list , So using this code i make sure the scrollviewer position is closer to selected wordSystem.Windows.Controls.Primitives.Selector selector = wordBankListView;
(selector as ListBox).ScrollIntoView(selector.SelectedItem);

Categories: Prsnl References Tags: ,

Async. Download progress bar c#

December 4, 2012 Leave a comment

The code for creating an async. download progress bar , allows user to track how much data is downloaded

WebClient client = new WebClient();

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);

client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

//// Starts the download

string folder_path =”Location to save file”;

client.DownloadFileAsync(new Uri(downloadUrl), folder_path,””);

void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)

{

double bytesIn = double.Parse(e.BytesReceived.ToString());

double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());

double percentage = bytesIn / totalBytes * 100;

 

downloadProgress.Text = int.Parse(Math.Truncate(percentage).ToString()).ToString()+” % finished”;

}

Categories: Prsnl References Tags: , , , ,

Custom Bindings in WPF simple example

November 2, 2011 Leave a comment

A complete tutorial on this topic is found on http://simonhartcher.com/2009/12/12/image-caching-for-a-wpf-desktop-application/  and you can read  the formatted version of the same blog here

For  developing a WPF Desktop Application that fetches images from a web server. One of the shortfalls of WPF is that client side caching is not implemented, but you can do it yourself using custom bindings.

Consider the following code where the binding ImageAddress points to an image on some web server (www.someserver.com/image.jpg):

<Image Source="{Binding ImageAddress}"/>

Each time the Window in which this code resides is loaded the image will be fetched from the web server.

Every time you say?! Every time…

Considering the application we are working on will be displaying a lot of images, this is just not acceptable.

using the Binding.Converter attribute I could pass the value of the Source attribute to a Converter and then back again.the path of local file or cached file.

To create a converter you create a class that implements IValueConverter requires that you implement two methods:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

Convert will be used to convert the data you pass to it into the desired format to display on the form. ConvertBack is the reverse, where any changes the user makes to the data displayed on the form may need to be converted back to a format that you require for processing (eg. to send to a database). Here is an example as provided on msdn: > The following example shows the implementation of a date converter that converts the date value passed in so that it only shows the year, the month, and the day. When implementing the IValueConverter interface, it is a good practice to decorate the implementation with a ValueConversionAttribute to indicate to development tools the data types involved in the conversion, as in the following example:

[ValueConversion(typeof(DateTime), typeof(String))]
public class DateConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    DateTime date = (DateTime)value;
    return date.ToShortDateString();
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    string strValue = value as string;
    DateTime resultDateTime;
    if (DateTime.TryParse(strValue, out resultDateTime))
    {
      return resultDateTime;
    }
    return DependencyProperty.UnsetValue;
  }
}

As you can see, in Convert value is cast to a DateTime object and then returned as a string using ToShortDateString(). Then in ConvertBack (which will be passed a string from the form) the string is parsed into a date using DateTime.TryParse() and then returned if it completes successfully.

So, onto the specific problem of caching an image on the local machine. I start with an empty class called ImageCacher implementing stub methods from IValueConverter. As we are grabbing the web address from a database, we are not interested in sending the local address back to the database, so we can simply complete ConvertBack returning a null value.

//Not needed – return null
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
  return null;// or  throw new NotImplementedException("Two way conversion is not supported.");
}

We then add the ValueConversionAttribute to indicate to development tools the data types involved in the conversion. This is not compulsory, but I think it also makes understanding what the converter is doing easier in a single glance. Our goal is to grab the string from the Source attribute and then pass one back with the updated image location (after we save it locally). So in this case, we are converting from a string to a string.

[ValueConversion(typeof(string), typeof(string))]
class ImageCacher : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
	
//Cast the string into a Uri so we can access the image name without regex
var uri = new Uri((String)value);
var localFile="";/find path of local file using own logic
if (!File.Exists(localFile))
{
	var request = HttpWebRequest.Create(uri);
	var response = (HttpWebResponse)request.GetResponse();
//check the content type to assert that the file in the uri is an image
if (!response.ContentType.StartsWith(“image”))
{
	throw new FileFormatException(uri, String.Format(“Uri passed to ImageCacher does not return an image. Content is of type {0}.”, response.ContentType));
}
	//load the image from the stream
	var image = Image.FromStream(response.GetResponseStream());
	//save it
	image.Save(localFile);
}

Finally, return the path to the local file.

	return localFile;
}

Then in XAML, reference our converter using an xmlns tag and add our converter in the resources area.

<Window x:Class=”MyImageCacher.Window1″
	xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
	xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
	xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
	xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″
	xmlns:con=”clr-namespace:MyImageCacher.ImageCacher”>
<Window.Resources>
<con:ImageCacher x:Key=”imageCacher”/>

Then we add the Converter attribute to the Binding of our original Image control.

<Image Source=”{Binding ImageAddress, Converter={StaticResource imageCacher}}“/>

And its as simple as that. Each time an address is passed to the control, it will run it through the converter first. It will check to see if the image exists locally, and download it if it hasn’t been.

 A complete tutorial on this topic is found on http://simonhartcher.com/2009/12/12/image-caching-for-a-wpf-desktop-application/  and you can read  the formatted version of the same blog here
Categories: Prsnl References Tags: ,