Thursday, May 17, 2012    
Blog  

OpenLight Blog

Silverlight Open File Dialog Behavior (MVVM)

Aug 15

Written by:
8/15/2010 5:34 PM  RssIcon

image

Live example: [at this link]

This Behavior will allow you to open a Silverlight File Dialog.

 

Here is your View Model:

using System;
using System.ComponentModel;
using System.Windows.Media.Imaging;
using System.IO;
 
namespace SilvelightViewModelOpenFileDialog
{
    public class MainPageModel : INotifyPropertyChanged
    {
        public MainPageModel()
        {
 
        }
 
        // Operations
        private void SetImage()
        {
            using (Stream stream = SelectedFileProperty.OpenRead())
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(stream);
                SelectedImageProperty = image;
            }
        }
 
        #region SelectedFileProperty
        private FileInfo _SelectedFileProperty;
        public FileInfo SelectedFileProperty
        {
            get
            {
                return this._SelectedFileProperty;
            }
            set
            {
                if (SelectedFileProperty == value)
                {
                    return;
                }
                _SelectedFileProperty = value;
                this.NotifyPropertyChanged("SelectedFileProperty");
                SetImage();
            }
        }
        #endregion
 
        #region SelectedImageProperty
        private BitmapSource _SelectedImageProperty;
        public BitmapSource SelectedImageProperty
        {
            get
            {
                return this._SelectedImageProperty;
            }
            set
            {
                if (SelectedImageProperty == value)
                {
                    return;
                }
 
                _SelectedImageProperty = value;
                this.NotifyPropertyChanged("SelectedImageProperty");
            }
        }
        #endregion
 
        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
 
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion
    }
}

 

Here is your UI:

image

Basically just put a Button on the page, and an Image control in a ScrollViewer.

image

Drop an OpenFileDialogBox Behavior on the Button.

image

Click Advanced options next to FileDialogDialogResultCommand.

image

Bind to the SelectedFileProperty and set Binding direction to TwoWay, and click OK.

image

In the Image Control, Click Advanced options next to Source.

image

Bind to the SelectedImageProperty and click OK.

The Behavior

image

To use the Behavior in your own projects, you need only to copy the OpenDialogbehavior.cs file.

Here is the full code for the Behavior:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
namespace OpenLightGroupBehaviors
{
    [System.ComponentModel.Description("Launches a Open File Dialog Box on Event Trigger")]
    public class OpenFileDialogBoxBehavior : TargetedTriggerAction<Button>
    {
        #region FileDialogDialogResultCommandProperty
        public static readonly DependencyProperty FileDialogDialogResultCommandProperty =
            DependencyProperty.Register("FileDialogDialogResultCommandProperty",
            typeof(object), typeof(OpenFileDialogBoxBehavior), null);
        public object FileDialogDialogResultCommand
        {
            get
            {
                return (object)base.GetValue(FileDialogDialogResultCommandProperty);
            }
            set
            {
                base.SetValue(FileDialogDialogResultCommandProperty, value);
            }
        }
        #endregion
        #region DialogFilterProperty
        public static readonly DependencyProperty DialogFilterProperty =
           DependencyProperty.Register("DialogFilter", typeof(string),
           typeof(OpenFileDialogBoxBehavior), null);
        public string DialogFilter
        {
            get
            {
                if (base.GetValue(DialogFilterProperty) == null)
                {
                    return "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg|"
                + "PNG Files (*.png)|*.png|All Files (*.*)|*.*";
                }
                else
                {
                    return (string)base.GetValue(DialogFilterProperty);
                }
            }
            set
            {
                base.SetValue(DialogFilterProperty, value);
            }
        }
        #endregion
        #region Invoke
        //Shows OpenFileDialog on event trigger you set in designer
        protected override void Invoke(object parameter)
        {
            OpenFileDialog objOpenFileDialog = new OpenFileDialog();
            objOpenFileDialog.Filter = DialogFilter;
            objOpenFileDialog.ShowDialog();
            FileDialogDialogResultCommand = objOpenFileDialog.File;
        }
        #endregion
    }
}

 

You can download the code here:
http://silverlight.adefwebserver.com/files/SilvelightViewModelOpenFileDialog.zip

15 comment(s) so far...


Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

Thank you.

By Denis on   8/17/2010 4:17 AM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

@Denis - Thanks for the comment. It is appreciated. It's the only 'payment' I get :)

By Michael Washington on   8/17/2010 4:49 AM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

I get an error message stating "Dialogs must be user-initiated." in the "Invoke" method of the Behavior. Am I doing something wrong?

By hattar on   8/23/2010 4:25 PM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

Nevermind :) Turns out I somehow had an extra OpenFileDialogBoxBehavior creep into my xaml. Works great, Thanks!

By hattar on   8/23/2010 4:25 PM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

I know it may sound a bit redundant ...
but what the heck... I'll say it again
USEFUL, CONCISE & VERY WELL EXPLAINED :)

BTW Do you have any future WP7 Beta projects in mind like the MVVM Video Player... ;)

Thank's for sharing your expertise. It's very appreciated

By MawashiKid on   8/26/2010 10:17 AM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

@MawashiKid - Thanks! However, no other WP7 planned for now.

By MawashiKid on   8/26/2010 10:18 AM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

I integrated your code (i.e. single .cs file) but _still_ get same security error when trying to open an local file via OpenFileDialog box, from any folder location. My understanding was that this solution was a work-around for not having to create an 'out-of-browser' Silverlight 4 app. Note that if I run your full C# app, I "CAN" load local photos/images just fine. Did I miss something? Specific error encountered is:

File operation not permitted. Access to path 'C:\Documents and Settings\mm\My Documents\mytestFiles\test-3.xml' is denied.

at System.IO.FileSecurityState.EnsureState()
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileInfo.Open(FileMode mode)
at OpenLightGroupBehaviors.OpenFileDialogBoxBehavior.Invoke(Object parameter)
at System.Windows.Interactivity.TriggerBase.InvokeActions(Object parameter)
at System.Windows.Interactivity.EventTriggerBase.OnEvent(EventArgs eventArgs)
at System.Windows.Interactivity.EventTriggerBase.OnEventImpl(Object sender, EventArgs eventArgs)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)

Appreciate the help!

By MM on   10/6/2010 5:14 AM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

@MM - My sample works for you right? The code must be triggered by a direct user interaction. The code does not (cannot) get around any security restrictions, it only eliminates the need to use code behind.

By Michael Washington on   9/16/2010 4:33 AM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

Hi again, and thanks for quick response.

Yes, but I already had working OpenFileDialog code in my SL4 C# project. I thought you figured out a way to get around the 'out-of-browser' security restriction. But, thinking about it now, obviously I was incorrect to think this. I planned for my browser app to support for local [XML-formatted] file saving (which work via SaveFileDialog w/o any security restrictions) _and_ the re-opening of such files back into the app.

Is my only option really to go the server storage path? SL4's temporary storage support (limited to only up to 1MB total file capacity) just won't do it -- and neither will the out-of-browser option because it will raise flags to customer IT folks re: network security.

Thanks for continuing this dialog (pun intended).
Mark

By MM on   9/16/2010 6:58 AM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

@MM - You can "request" more storage space from the user. I have no examples but you can Google it.

By Michael Washington on   9/16/2010 6:59 AM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

OK, I'll investigate that. Thanks again.

By MM on   9/16/2010 9:55 AM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

Cool approach, well done!

A similar Behaviour for Save File Dialog will also be very useful :-)

LarsM

By LarsM on   9/21/2010 1:28 PM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

Very helpful

By Jimmy Dickinson on   10/8/2010 12:13 PM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

What an elegant solution. Thank you.

By Ankur Anand on   8/19/2011 10:37 AM
Gravatar

Re: Silverlight Open File Dialog Behavior (MVVM)

very good! appreciate it !!!

By Leon on   10/15/2011 7:45 PM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 
  
Copyright 2009 by OpenLightGroup.net   |  Privacy Statement  |  Terms Of Use