Click here to Skip to main content
Click here to Skip to main content

Silverlight : Simple PopUp Behavior for VM, MVVM

By , , 1 Sep 2010
 

A Behavior created by Haruhiro Isowa with assistance from Michael Washington.

Introduction

This article will show you how to use my PopUp Behavior that will launch a simple Yes/No Popup and explain how it works so you will be able to tune it to your needs. This PopUp should make creating PopUps in MVVM / VM style easier by generating the PopUp for you which will save you the time of creating a View and View Model for a Popup, remove the need for complexity shown by other solutions that uses messaging / services and so forth. This also allows designers to have some control to create PopUps without waiting for the programmers to make a View and VM for them.

What HisowaSimplePopUpBehavior Do

This is the PopUp that it generates, but you can customize by modding the code or by properties on behavior.

sample\

These are the Properties. (All properties under Miscellaneous are bindable).

Properties

  • Brushes are to set your background of the Buttons and PopUp Window, gradients, images, etc. are ok.
  • CustomParameter: object, you pass to the behavior and when the PopUp closes it will return that to you. You can pass selected object or ID, etc.
  • PopUpMessage: string, set the message for the PopUp
  • PopUpNoMessage: string, set the text on the No button
  • PopUpYesMessage: string, set the text on the Yes button
  • ReturnDialogResult: bool?, exposes the result of the PopUp (You can use two-way binding to pass back results. I used it to set IsChecked on a checkbox.
  • ReturnICommand: ICommand, The command to run when PopUp closes. It will pass in a dataholder class HisowaSimplePopUpBehaviorResult which will contain the DialogResult (bool?), DataContext of the Popup (Probably will not be used for this Popup Behavior ver), and InputParameter which is your CustomParameter you have set above.

By the properties of the behavior, you probably can guess what is going to happen. This Behavior will generate a simple Popup that you can set text, background values; pass in a parameter (probably useful to put the object in question); allow you to bind the DialogResult of the PopUp; and Most importantly run an ICommand when the PopUp Closes and passes you the DialogResult, DataContext, and the parameter you have passed so your ICommand can consume it.

Using my HisowaSimplePopUpBehavior

Start by opening a new Silverlight Application. Name it SimplePopUpBehaviorSample. Add my HisowaSimplePopUpBehavior class to your solution. Add a reference to System.Windows.Interactivity, and System.Windows.Controls. System.Windows.Interactivty is in Blend SDK. Build your project and open your MainPage.xaml in Expression Blend.

Before we can get started, we will need to have a View and ViewModel. Delete the MainPage.xaml in Blend. Add a new Item to the project by Right Clicking on the Project, select Add New Item. On the dialog, set User Control with ViewModel, name the file MainPage.xaml.

New Vm

Open the MainPage.xaml.

Drag a button on the page. Then look for my behavior HisowaSimplePopUpBehavior and drag it on the Button.

.behavior

Now Build and run it from Blend. You should now have a simple Popup. At this point, it's not doing anything cool.

ViewModel Code

We need to setup some code in the ViewModel. But before we get started, we will use John Papa's DelegateCommand.cs file. Get it from Delegate Command From John Papa.

Replace MainPageModel.cs code with this:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Data;
using System.ComponentModel;
using System.Windows.Input;
using HisowaPopUpBehaviors;

namespace SimplePopUpBehaviorSample
{
    public class MainPageModel : INotifyPropertyChanged
    {
        public MainPageModel()
        {
            PopupSimpleResultCommand = new DelegateCommand
            (PopupSimpleResult, CanPopupSimpleResult);
        }

        #region PopupSimpleResultCommand
        public ICommand PopupSimpleResultCommand { get; set; }
        public void PopupSimpleResult(object param)
        {
            //cast to my DataContainer
            HisowaSimplePopUpBehaviorResult _result = 
            (HisowaSimplePopUpBehaviorResult)param;

            //get the dialogResult
            PopUpResult = _result.DialogResult;

            //get the input if exists
            if (_result.InputParameter != null)
            {
                Message = _result.InputParameter.ToString();
            }
        }

        private bool CanPopupSimpleResult(object param)
        {
            return true;
        }
        #endregion

        #region PopUpResult
        private bool? _PopUpResult;
        public bool? PopUpResult
        {
            get
            {
                return _PopUpResult;
            }
            set
            {
                _PopUpResult = value;
                this.NotifyPropertyChanged("PopUpResult");
            }
        }
        #endregion

        #region Message
        private string _Message;
        public string Message
        {
            get { return _Message; }
            private set
            {
                if (Message == value)
                {
                    return;
                }
                _Message = value;
                this.NotifyPropertyChanged("Message");
            }
        }
        #endregion

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion
    }
}

This is just a simple VM that has single ICommand that sets the Popup result to the properties (string Message, bool? PopupResult). It also implements INotifyPropertyChanged.

*Note: You might need to fix namespaces if you didn't use the same name for the project.

Now Build and let's get back to Blend.

Using the Behavior part2, with Properties

Now that we got all the groundwork done, we can start using the HisowaSimplePopUpBehavior to its full potential.

First, we will need to make a UI similar to this for this demo.

UI

Bind these Text Values with Element Property Binding.

  • PopUpMessage: Your message Textbox's Text property
  • PopUpYes/NoMessage: Your Textbox's Text property
  • CustomParameter: Your Input Textbox's Text property (this allows object, it can be anything)

elemntbind

Bind ReturnDialogResult to Checkbox's IsChecked Property, two-way binding.

two

Build and Run. Now you should be able to change the text on your TextBox to what you typed in the textbox. The CheckBox should be checked if the popup was closed by the yes button.

sample

Should look like this.

Now we would like to set ReturnICommand the most important part of the Behavior. To do this, Databind the ReturnIcommand to the PopUpSimpleResultCommand and Build.

icom - Click to enlarge image

To check that it's working, go back to Visual Studio and put a breakpoint somewhere in the ICommand you binded. Then Debug in Visual Studio.

deb

Notice that Icommand is getting HisowaPopUpBehaviors class which holds the DialogResult, InputParameter(CustomParameter) and DataContext. You should be able to do a lot with these in your ICommand.

My Behavior Explained

In this section, I will explain the code of the Behavior. Most of them are dependency properties that allow the databindings, so I will skip over those.

This is the Invoke method, this gets called when the trigger is fired.

#region Invoke

        //Shows popup on event trigger you set in designer

        protected override void Invoke(object parameter)
        {
            ChildWindow _childWindow = new ChildWindow();
            _grid = new Grid();

            _grid.Width = 300;
            _grid.Height = 100;

            //width 3 cols
            _grid.ColumnDefinitions.Add(new ColumnDefinition() 
        { Width = new GridLength(1, GridUnitType.Star) });
            _grid.ColumnDefinitions.Add(new ColumnDefinition() 
        { Width = new GridLength(1, GridUnitType.Star) });
            _grid.ColumnDefinitions.Add(new ColumnDefinition() 
        { Width = new GridLength(1, GridUnitType.Star) });

            //height 3 rows
            _grid.RowDefinitions.Add(new RowDefinition() 
        { Height = new GridLength(1, GridUnitType.Star) });
            _grid.RowDefinitions.Add(new RowDefinition());
            _grid.RowDefinitions.Add(new RowDefinition());

            //add message
            TextBlock tbkMessage = new TextBlock();
            tbkMessage.Text = PopUpMessage;
            tbkMessage.SetValue(Grid.RowProperty, 0);
            tbkMessage.SetValue(Grid.ColumnProperty, 0);
            tbkMessage.SetValue(Grid.ColumnSpanProperty, 3);

            _grid.Children.Add(tbkMessage);

            //add Yes button
            Button btnYes = new Button();
            btnYes.Content = PopUpYesMessage;
            btnYes.SetValue(Grid.ColumnProperty, 0);
            btnYes.SetValue(Grid.RowProperty, 1);
            btnYes.Name = "btnYes";
            btnYes.Click += new RoutedEventHandler(btnYes_Click);

            _grid.Children.Add(btnYes);

            //add No Button
            Button btnNo = new Button();
            btnNo.Content = PopUpNoMessage;
            btnNo.SetValue(Grid.ColumnProperty, 2);
            btnNo.SetValue(Grid.RowProperty, 1);
            btnNo.Name = "btnNo";
            btnNo.Click += new RoutedEventHandler(btnNo_Click);

            _grid.Children.Add(btnNo);

            //style
            _grid.Background = BackGroundColorParameter;
            btnYes.Background = YesColorParameter;
            btnNo.Background = NoColorParameter;

            //Make it a PopUp
            _childWindow.Content = _grid;

            PopUp = _childWindow;

            PopUp.Closing += new EventHandler<canceleventargs />(PopUp_Closing);

            PopUp.Show();

        }

        #endregion    

Basically it creates the UI, sets the event handlers and assigns the properties from the behavior such as background and message. This is where you will tweak to change the UI.

Now the event handling code for the Yes/No buttons.

#region BtnClicks

        void btnNo_Click(object sender, RoutedEventArgs e)
        {
            RemoveButtonHandlers();
            PopUp.DialogResult = false;
        }

        void btnYes_Click(object sender, RoutedEventArgs e)
        {
            RemoveButtonHandlers();
            PopUp.DialogResult = true;
        }

        private void RemoveButtonHandlers()
        {
            Button btnYes = (Button)_grid.FindName("btnYes");
            btnYes.Click -= new RoutedEventHandler(btnYes_Click);

            Button btnNo = (Button)_grid.FindName("btnNo");
            btnNo.Click -= new RoutedEventHandler(btnNo_Click);
        }

        #endregion

This sets the DialogResults which also closes the PopUp, and removes the event handlers.

Now the code for PopUpClosing event:

#region ChildwindowClosing

        //Runs an Icommand when the Popup is closing
        //you can change what it passes to Icommand to whatever you like
        //be sure that your method can consume them


        void PopUp_Closing(object sender, CancelEventArgs e)
        {
            PopUp.Closing -= new EventHandler<canceleventargs />(PopUp_Closing);

            ReturnDialogResultCommand = PopUp.DialogResult;

            if (ReturnICommand != null)
            {
                HisowaSimplePopUpBehaviorResult _result = 
			new HisowaSimplePopUpBehaviorResult();
                _result.DialogResult = PopUp.DialogResult;
                _result.DataContext = PopUp.DataContext;
                _result.InputParameter = CustomParameter;

                ReturnICommand.Execute(_result);
            }
        }

        #endregion

All this does is remove the handler, get the Icommand from the dependency property, create my datacontainer HisowaSimplePopUpBehaviorResult, and run the Icommand passing the HisowaSimplePopUpBehaviorResult.

Lastly, the DataContainer HisowaSimplePopUpBehaviorResult class which is in the same file.

public class HisowaSimplePopUpBehaviorResult
    {
        public bool? DialogResult { get; set; }
        public object DataContext { get; set; }
        public object InputParameter { get; set; }
    }

This is just a simple data holder.

Full Code

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.ComponentModel;
using System.Reflection;

namespace HisowaPopUpBehaviors
{
    [System.ComponentModel.Description("Launches a Simple Popup on Event Trigger")]
    public class HisowaSimplePopUpBehavior : TargetedTriggerAction<frameworkelement />, 
    INotifyPropertyChanged
    {
        private ChildWindow PopUp;
        Grid _grid = new Grid();

        //constructor
        public HisowaSimplePopUpBehavior()
        { }

        #region CustomParameterProperty
        public static readonly DependencyProperty CustomParameterProperty = 
    DependencyProperty.Register("CustomParameter", typeof(object), 
    typeof(HisowaSimplePopUpBehavior), null);

        public object CustomParameter
        {
            get
            {
                return base.GetValue(CustomParameterProperty);
            }
            set
            {
                base.SetValue(CustomParameterProperty, value);
            }
        } 
        #endregion

        #region ReturnDialogResultCommandProperty

        public static readonly DependencyProperty ReturnDialogResultCommandProperty = 
    DependencyProperty.Register("ReturnDialogResultCommand", typeof(bool?), 
    typeof(HisowaSimplePopUpBehavior), null);

        public bool? ReturnDialogResultCommand
        {
            get
            {
                return (bool?)base.GetValue(ReturnDialogResultCommandProperty);
            }
            set
            {
                base.SetValue(ReturnDialogResultCommandProperty, value);
                this.NotifyPropertyChanged("ReturnDialogResultCommand");
            }
        }
        #endregion

        #region ReturnICommandProperty

        public static readonly DependencyProperty ReturnICommandProperty = 
    DependencyProperty.Register("ReturnICommand", typeof(ICommand), 
    typeof(HisowaSimplePopUpBehavior), null);

        public ICommand ReturnICommand
        {
            get
            {
                return (ICommand)base.GetValue(ReturnICommandProperty);
            }
            set
            {
                base.SetValue(ReturnICommandProperty, value);
            }
        }
        #endregion

        #region PopUpMessageProperty

        public static readonly DependencyProperty PopUpMessageProperty = 
    DependencyProperty.Register("PopUpMessage", typeof(string), 
    typeof(HisowaSimplePopUpBehavior), null);

        public string PopUpMessage
        {
            get
            {
                if (base.GetValue(PopUpMessageProperty) == null)
                {
                    return "Are you sure?";
                }
                else
                {
                    return (string)base.GetValue(PopUpMessageProperty);
                }
            }
            set
            {
                base.SetValue(PopUpMessageProperty, value);
            }
        }

        #endregion

        #region PopUpYesMessageProperty

        public static readonly DependencyProperty PopUpYesMessageProperty = 
    DependencyProperty.Register("PopUpYesMessage", typeof(string), 
    typeof(HisowaSimplePopUpBehavior), null);

        public string PopUpYesMessage
        {
            get
            {
                if (base.GetValue(PopUpYesMessageProperty) == null)
                {
                    return "Yes";
                }
                else
                {
                    return (string)base.GetValue(PopUpYesMessageProperty);
                }
            }
            set
            {
                base.SetValue(PopUpYesMessageProperty, value);
            }
        }

        #endregion

        #region PopUpNoMessageProperty

        public static readonly DependencyProperty PopUpNoMessageProperty = 
    DependencyProperty.Register("PopUpNoMessage", typeof(string), 
    typeof(HisowaSimplePopUpBehavior), null);

        public string PopUpNoMessage
        {
            get
            {
                if (base.GetValue(PopUpNoMessageProperty) == null)
                {
                    return "No";
                }
                else
                {
                    return (string)base.GetValue(PopUpNoMessageProperty);
                }
            }
            set
            {
                base.SetValue(PopUpNoMessageProperty, value);
            }
        }

        #endregion

        #region BackgroundColor
        public static readonly DependencyProperty BackGroundColorParameterProperty = 
    DependencyProperty.Register("BackGroundColorParameter", 
    typeof(System.Windows.Media.Brush), typeof(HisowaSimplePopUpBehavior), null);

        public System.Windows.Media.Brush BackGroundColorParameter
        {
            get
            {
                return (System.Windows.Media.Brush)base.GetValue
            (BackGroundColorParameterProperty);
            }
            set
            {
                base.SetValue(BackGroundColorParameterProperty, value);
            }
        }
        #endregion

        #region YesColor
        public static readonly DependencyProperty YesColorParameterProperty = 
    DependencyProperty.Register("YesColorParameter", 
    typeof(System.Windows.Media.Brush), typeof(HisowaSimplePopUpBehavior), null);

        public System.Windows.Media.Brush YesColorParameter
        {
            get
            {
                return (System.Windows.Media.Brush)base.GetValue
            (YesColorParameterProperty);
            }
            set
            {
                base.SetValue(YesColorParameterProperty, value);
            }
        }
        #endregion

        #region NoColor
        public static readonly DependencyProperty NoColorParameterProperty = 
    DependencyProperty.Register("NoColorParameter", 
    typeof(System.Windows.Media.Brush), typeof(HisowaSimplePopUpBehavior), null);

        public System.Windows.Media.Brush NoColorParameter
        {
            get
            {
                return 
		(System.Windows.Media.Brush)base.GetValue(NoColorParameterProperty);
            }
            set
            {
                base.SetValue(NoColorParameterProperty, value);
            }
        }
        #endregion

        #region Invoke

        //Shows popup on event trigger you set in designer

        protected override void Invoke(object parameter)
        {
            ChildWindow _childWindow = new ChildWindow();
            _grid = new Grid();

            _grid.Width = 300;
            _grid.Height = 100;

            //width 3 cols
            _grid.ColumnDefinitions.Add(new ColumnDefinition() 
        { Width = new GridLength(1, GridUnitType.Star) });
            _grid.ColumnDefinitions.Add(new ColumnDefinition() 
        { Width = new GridLength(1, GridUnitType.Star) });
            _grid.ColumnDefinitions.Add(new ColumnDefinition() 
        { Width = new GridLength(1, GridUnitType.Star) });

            //height 3 rows
            _grid.RowDefinitions.Add(new RowDefinition() 
        { Height = new GridLength(1, GridUnitType.Star) });
            _grid.RowDefinitions.Add(new RowDefinition());
            _grid.RowDefinitions.Add(new RowDefinition());

            //add message
            TextBlock tbkMessage = new TextBlock();
            tbkMessage.Text = PopUpMessage;
            tbkMessage.SetValue(Grid.RowProperty, 0);
            tbkMessage.SetValue(Grid.ColumnProperty, 0);
            tbkMessage.SetValue(Grid.ColumnSpanProperty, 3);

            _grid.Children.Add(tbkMessage);

            //add Yes button
            Button btnYes = new Button();
            btnYes.Content = PopUpYesMessage;
            btnYes.SetValue(Grid.ColumnProperty, 0);
            btnYes.SetValue(Grid.RowProperty, 1);
            btnYes.Name = "btnYes";
            btnYes.Click += new RoutedEventHandler(btnYes_Click);

            _grid.Children.Add(btnYes);

            //add No Button
            Button btnNo = new Button();
            btnNo.Content = PopUpNoMessage;
            btnNo.SetValue(Grid.ColumnProperty, 2);
            btnNo.SetValue(Grid.RowProperty, 1);
            btnNo.Name = "btnNo";
            btnNo.Click += new RoutedEventHandler(btnNo_Click);

            _grid.Children.Add(btnNo);

            //style
            _grid.Background = BackGroundColorParameter;
            btnYes.Background = YesColorParameter;
            btnNo.Background = NoColorParameter;

            //Make it a PopUp
            _childWindow.Content = _grid;

            PopUp = _childWindow;

            PopUp.Closing += new EventHandler<canceleventargs />(PopUp_Closing);

            PopUp.Show();
        }

        #endregion

        #region BtnClicks

        void btnNo_Click(object sender, RoutedEventArgs e)
        {
            RemoveButtonHandlers();
            PopUp.DialogResult = false;
        }

        void btnYes_Click(object sender, RoutedEventArgs e)
        {
            RemoveButtonHandlers();
            PopUp.DialogResult = true;
        }

        private void RemoveButtonHandlers()
        {
            Button btnYes = (Button)_grid.FindName("btnYes");
            btnYes.Click -= new RoutedEventHandler(btnYes_Click);

            Button btnNo = (Button)_grid.FindName("btnNo");
            btnNo.Click -= new RoutedEventHandler(btnNo_Click);
        }

        #endregion

        #region ChildwindowClosing

        //Runs an Icommand when the Popup is closing
        //you can change what it passes to Icommand to whatever you like
        //be sure that your method can consume them


        void PopUp_Closing(object sender, CancelEventArgs e)
        {
            PopUp.Closing -= new EventHandler<canceleventargs />(PopUp_Closing);

            ReturnDialogResultCommand = PopUp.DialogResult;

            if (ReturnICommand != null)
            {
                HisowaSimplePopUpBehaviorResult _result = 
            new HisowaSimplePopUpBehaviorResult();
                _result.DialogResult = PopUp.DialogResult;
                _result.DataContext = PopUp.DataContext;
                _result.InputParameter = CustomParameter;

                ReturnICommand.Execute(_result);
            }
        }

        #endregion

        // Utility

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion
    }

    public class HisowaSimplePopUpBehaviorResult
    {
        public bool? DialogResult { get; set; }
        public object DataContext { get; set; }
        public object InputParameter { get; set; }
    }
} 

Also see: HisowaModPopUpBehavior

This variation will allow you to use your own View and View Model and inject it into the popup.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

About the Authors

defwebserver
Software Developer (Senior) http://ADefWebserver.com
United States United States
Member
Michael Washington is a Microsoft Silverlight MVP. He is a Silverlight developer and an ASP.NET, C#, and Visual Basic programmer.
 
He is a DotNetNuke Core member and has been involved with DotNetNuke for over 4 years. He is the Co-Author of Building Websites with DotNetNuke (4 and 5).
 
He is one of the founding members of The Open Light Group (http://openlightgroup.net).
 
He is the founder of http://LightSwitchHelpWebsite.com
 
He has a son, Zachary and resides in Los Angeles with his wife Valerie.

hisowa
Software Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow to control opening popup from viewmodelmemberLibnosis26 Apr '12 - 5:17 
I am new to Silverlight so forgive me if the answer is obvious. I have a button on my view bound to a command in my vm. I would like to use your popup behavior to show a message to the user based on a RIA service call being successful or not.
 
Here's my code that uses RIA services to save my changes to the db...
public void SaveData()
        {
            IsBusy = true;
            Context.SubmitChanges(SaveCompleted, null);
        }
 
Here's my code to see if the save operation was successful...
private void SaveCompleted(SubmitOperation so)
        {
            IsBusy = false;
 
            if (so.HasError)
            {
                so.MarkErrorAsHandled();
                // This is where I want to popup a window using your behavior.
            }
        }
 
If you could help me understand if this is possible or point me in the right direction I would be grateful.
 
Mark
 
PS Great Article!
AnswerRe: How to control opening popup from viewmodelmemberhisowa26 Apr '12 - 21:04 
Unfortunately none of my popup are designed for that purpose. As you can tell it was to get in between the user interaction and running the VM method. So the following is suggestions are ideas
 
Basically try out different triggers settings.
1. Create a event to run @ // This is where... in the VM
2. add HisowaSimplePopupBehavior to your xaml
3. goto behavior properties > trigger section and set SourceObject to your VM
4. set Event name property to the event you made in step 1.
 
ex: the behavior's trigger is an Event trigger. If the event it binds to fires it will open the popup. By setting the source object to your VM it will now look into the VM for events which allows you to bind it. So fire the event @ // This is where...
 
another way
Another Ver of Popup Behavior[^]
 
1. have a property that you change @ // This is where...
2. Change trigger type to Property changed Trigger (click New button select it)
3. Set the Binding to the property in step 1
 
// That should get you some ideas.
I tried it out a bit on the sample projects and it does show the popups. It does need some refinements tho Frown | :( .
 
Sorry I couldn't be much of help. I haven't worked on these for a long time.
GeneralRe: How to control opening popup from viewmodelmemberLibnosis27 Apr '12 - 1:59 
I got it to work! I'm learning Blend too so this is lots of fun and frustrating at times. I created a datatrigger in the xaml file and bound it to a property on the vm that holds the error messages. The trigger compares the value of the error messages property to the empty string. If its not empty the datatrigger will fire. When it fires I use your behavior. I bind PopUpMessage to the error message I want to display. I bind PopUpYesMessage to "Ok" because I'm only using one button. I bind the ReturnICommand property to a command on the vm to reset the error message back to the empty string. Now when RIA services sends back an error from the db I can pop it in my error message property and display it to the user and still keep a clean MVVM!
 
Here's the xaml I used...
<i:Interaction.Triggers>
                <ei:DataTrigger Binding="{Binding ErrorMessages}"
                                Comparison="NotEqual"
                                Value="">
                    <SilverlightApplication9:PopUpBehavior PopUpMessage="{Binding ErrorMessages}" PopUpYesMessage="Ok" ReturnICommand="{Binding ResetErrorMsgCommand, Mode=OneWay}" />
                </ei:DataTrigger>
            </i:Interaction.Triggers>
 
Thanks again for your help and ideas.
Mark
QuestionParameter & Yes/No Button in CustomUImemberwillyraharja1 Jun '11 - 7:40 
hi, im fairly new to silverlight. refer to html style like query string and popup. is that possible to passing parameter to the usercontol in CustomUI? how to make some button in CustomUI behaviour like yes/no button? I'm trying to make this as a container for complex form, for example i have customer grid, and when i click edit button, popup user form is show up, edit it... when i click save/cancel.. it will close the popup. btw this article is great. 5 for u Smile | :) thx
AnswerRe: Parameter & Yes/No Button in CustomUImemberhisowa1 Jun '11 - 8:49 
I have other articles that features a variations that might suit your needs.
 
I have a ModPopUpBehavior which allows you to
1) Make your own UI (except the 'yes/no' buttons, this is made for you)
2) Allow you to use your own datacontext for the popup
3) passes back the data context of your popup to consume on the main form.
 
however this does not solve your
1) pass parameter into popup, but some tweaking might fix that (haven't worked on this for awhile, cant give you a clear answer).
-- i think you can replace the datacontext on invoke.
 
http://openlightgroup.net/Blog/tabid/58/EntryId/123/Silverlight-Behavior-HisowaModPopUpBehavior.aspx[^]
 
I think i had a better one which I haven't bothered to post yet, I will look for it once i get home.
GeneralRe: Parameter & Yes/No Button in CustomUImemberwillyraharja1 Jun '11 - 19:28 
Hi Hisowa, thx for the fast reply. Really sorry, i should post this msg to "HisowaModPopUpBehaviour" which actually i'm trying to use. Should i move to that one?
 
Yup, the datacontext... i've been thinking use that, but don't know how to use it as input parameter Confused | :confused: For the pop up result, it works great.
 
For the own UI (CustomUI) i had easily injected my ow ui (Thumbs Up | :thumbsup: for u) but i confused how to make a button close the ui. I need to put the button in my own ui because it also have another process specified to the form. All i know DialogResult can handle this, but since my UI derived from usercontrol which don't have DialogResult.
GeneralRe: Parameter & Yes/No Button in CustomUImemberhisowa2 Jun '11 - 19:36 
I rushed out a post with the newer version of the popup behavior. It took a lot more time to dig up than expected, sorry bout that. // it was on the shelf for months collecting dust.
 
Blog Post[]
 
(that is supplementing the last post)
 
Prev Post[]
 
To sum it all up this one you can make your own childwindow, so you get full control of the code behind, ui (Yes, No Button) and so forth. The code behind is actually set the dialog results.
 
Passing the parameters, I am still tinkering with it from last night and not being successful with it. Cry | :((
Propertyname thing might be useful in pass it back. do the reverse of when I'm invoking the ReturnIcommand. Hopefully you can find a way. I will tinker for a bit longer too.
GeneralRe: Parameter & Yes/No Button in CustomUImemberwillyraharja3 Jun '11 - 3:39 
Hi, thx Isowa. Im able to pass using property. Using property similar to "CustomParameter" in HisowaSimplePopUp and feed them to datacontext.
 

protected override void Invoke(object parameter)
{
ChildPopUp = (ChildWindow)Activator.CreateInstance(CustomChildWindow.GetType());
ChildPopUp.DataContext = CustomParameter;
ChildPopUp.Show();
 
ChildPopUp.Closing += new EventHandler<CancelEventArgs>(ChildPopUp_Closing);
}

 
I put the button in my column datagrid binding to my MemberList

<Button Content="V2 Launcher" HorizontalAlignment="Left" Margin="32,16,0,0" VerticalAlignment="Top" Width="112">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<my:PopUpProtoV2 PropertyName="ChildDataObject" ReturnICommand="{Binding Source={StaticResource ViewModel}, Path=MemberPopupResultCommand}" CustomParameter="{Binding}">
<my:PopUpProtoV2.CustomChildWindow>
<views:Member />
</my:PopUpProtoV2.CustomChildWindow>
</my:PopUpProtoV2>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>

 
But the bad news is i think this is bad practices because i must create 2 ViewModel object for every row in my grid. 1 for the default vm in my view (maybe i must create fake empty vm) and 1 for CustomParamter.
Maybe this is not a big performance issue when i only use 1 button. but since i use in datagarid there will be 'n' button as datagrid pagesize.
 
Right now i'm searching the workaround how to solve this. Because i really new to SL, seems i need sometime. So i just post what i had found (include the problem Blush | :O )
GeneralRe: Parameter & Yes/No Button in CustomUImemberhisowa5 Jun '11 - 20:53 
Can you not bind it the datacontext / object of the grid item? Unfortunately I am not great with the binding stuff.
AnswerRe: Parameter & Yes/No Button in CustomUImemberhisowa6 Jun '11 - 20:47 
http://hisowa.adefwebserver.com/blogs/Samples/Temp/PopupBehaviorProtoTestPage.html
 
http://hisowa.adefwebserver.com/blogs/Files/Temp/PopupBehaviorProtoV3.zip
 
Took a while but heres my stuff. (you probably got it to work by now so its also for other people who might have the same issues)
1) Added a data list, all collection of dataobjectcontainers to main VM
2) click button to edit it. The Parameter to pass is binded to the datagrid item. (edit additional template ...) So the value gets passed in and back. No Dummy VM
3) I took pretty much the same approach to passing the VM, the difference is where. You passed it to Datacontext while I passed it to the property of the datacontext.
 
hopefully this helps.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 1 Sep 2010
Article Copyright 2010 by defwebserver, hisowa
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid