Sunday, March 4, 2012

Binding with StringFormat

With Silverlight, when you bind a property, you can use StringFormat to format the display.
{Binding SampleText, StringFormat='My Text: \{0\}'}

Strings

You can use StringFormat like the c# String.Format() method.

Composite Formatting

Numbers

CTo display a currency. ex: StrinFormat=C –> $300.00
NTo display a number. ex: StringFormat=N –> 33,456.56
ETo display a scientific number. ex: StringFormat=E –> 6.787653e+006
PTo display a percentage. This value must be between 0 and 1. ex: StringFormat=P –> 33.54%

Standard Numeric Format Strings
Custom Numeric Format Strings

DateTimes

FStringFormat=F –> Sunday, March 04, 2012 4:22:09 PM
GStringFormat=G –> 3/4/2012 4:22:09 PM
MStringFormat=M –> March 04

You can also use the format like “MMMM yyyy” but it must be between ‘ ex: StringFormat=’MMMM yyyy’

Standard date and Time Format Strings
Custom Date and Time Format Strings

Catch the silverlight closing event

Recently, I must catch the closing event of a silverlight application when users have not save their modifications. For this functionnality, I make a class with a boolean indicate pending changes.
public class ClosingHandler
{
    #region Properties
 
    private const string ScriptableObjectName = "OnBeforeUnload";
 
    /// <summary>
    /// Confirmation message
    /// </summary>
    public String Message { get; set; }
 
    private Boolean mHasPendingChange;
    /// <summary>
    /// Indicate pending change
    /// </summary>
    public Boolean HasPendingChange
    {
        get { return mHasPendingChange; }
        set
        {
            mHasPendingChange = value;
            if (value)
                Initialize();
            else
                Clear();
        }
    }
 
    #endregion
 
    #region Methods
 
    /// <summary>
    /// Initialization of the Hander
    /// </summary>
    public void Initialize()
    {
        //Out of Browser application
        if (Application.Current.IsRunningOutOfBrowser)
        {
            Application.Current.MainWindow.Closing +=
                new EventHandler<System.ComponentModel.ClosingEventArgs>(
                    MainWindow_Closing);
        }
        else    //In Browser application
        {
            HtmlPage.RegisterScriptableObject(ScriptableObjectName, this);
            string pluginName = HtmlPage.Plugin.Parent.Id;
 
            HtmlPage.Window.Eval(string.Format(
                @"window.onbeforeunload = function () {{
                var slApp = document.getElementById('{0}').getElementsByTagName('object')[0];
                var result = slApp.Content.{1}.OnBeforeUnload();
                if(result.length > 0)
                    return result;
                }}",
                pluginName, ScriptableObjectName)
                );
        }
    }
 
    /// <summary>
    /// Clear event handler and message
    /// </summary>
    public void Clear()
    {
        //Out of Browser application
        if (Application.Current.IsRunningOutOfBrowser)
        {
            Application.Current.MainWindow.Closing -=
                new EventHandler<System.ComponentModel.ClosingEventArgs>(
                    MainWindow_Closing);
        }
        else    //In Browser application
        {
            HtmlPage.RegisterScriptableObject(ScriptableObjectName, this);
            string pluginName = HtmlPage.Plugin.Parent.Id;
 
            HtmlPage.Window.Eval(@"window.onbeforeunload = ''");
        }
    }
 
    #endregion
 
    #region EventHandler
 
    /// <summary>
    /// MainWindow Closing event handler
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void MainWindow_Closing(object sender, System.ComponentModel.ClosingEventArgs e)
    {
        MessageBoxResult boxResult = MessageBox.Show(
                    Message, "Closing confirmation",
                    MessageBoxButton.OKCancel);
        if (boxResult == MessageBoxResult.Cancel)
            e.Cancel = true;
    }
 
    [ScriptableMember]
    public string OnBeforeUnload()
    {
        return Message;
    }
 
    #endregion
}

Source : http://mark.mymonster.nl/2011/01/30/how-to-cancel-the-closing-of-your-silverlight-application-in-browser-and-out-of-browser

Friday, March 2, 2012

DelegateCommand in Silverlight

public class DelegateCommand : ICommand
{
    /// <summary>
    /// Occurs when changes occur that affect whether the command should execute.
    /// </summary>
    public event EventHandler CanExecuteChanged;
 
    Func<objectbool> canExecute;
    Action<object> executeAction;
    bool canExecuteCache;
 
    /// <summary>
    /// Initializes a new instance of the <see cref="DelegateCommand"/> class.
    /// </summary>
    /// <param name="executeAction">The execute action.</param>
    /// <param name="canExecute">The can execute.</param>
    public DelegateCommand(Action<object> executeAction,
                            Func<objectbool> canExecute)
    {
        this.executeAction = executeAction;
        this.canExecute = canExecute;
    }
 
    /// <summary>
    /// Permet de déclencher l'evenement de modification du CanExecute
    /// </summary>
    public void OnCanExecuteChanged()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(thisnew EventArgs());
    }
 
    #region ICommand Members
    /// <summary>
    /// Defines the method that determines whether the command 
    /// can execute in its current state.
    /// </summary>
    /// <param name="parameter">
    /// Data used by the command. 
    /// If the command does not require data to be passed,
    /// this object can be set to null.
    /// </param>
    /// <returns>
    /// true if this command can be executed; otherwise, false.
    /// </returns>
    public bool CanExecute(object parameter)
    {
        bool tempCanExecute = canExecute(parameter);
 
        if (canExecuteCache != tempCanExecute)
        {
            canExecuteCache = tempCanExecute;
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(thisnew EventArgs());
            }
        }
 
        return canExecuteCache;
    }
 
    /// <summary>
    /// Defines the method to be called when the command is invoked.
    /// </summary>
    /// <param name="parameter">
    /// Data used by the command. 
    /// If the command does not require data to be passed, 
    /// this object can be set to null.
    /// </param>
    public void Execute(object parameter)
    {
        executeAction(parameter);
    }
    #endregion
} 

Source : http://compositewpf.codeplex.com/