.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

MVVM how to move event handler from code behind to ViewModel

Posted By:      Posted Date: October 05, 2010    Points: 0   Category :WPF

First of all I'm fairly new to WPF and MVVM. For learning purposes I created a very simple MVVM test app similar to the one demonstrated here: http://windowsclient.net/learn/video.aspx?v=314683

I am trying to find out how to work with events in the MVVM pattern. To work with events in the xaml code behind is simple. But how to move the code to the ViewModel?

In the xaml I have:

    <StackPanel Background="{Binding BackgroundBrush}">
        <ItemsControl ItemsSource="{Binding AllEmployees}">
                    <StackPanel Orientation="Horizontal">
                        <TextBox Width="100" Text="{Binding FirstName}" />
                        <TextBox Width="100&q

View Complete Post

More Related Resource Links

Creating Event Handler in Code behind


Hi, so I have a control that is created in the code behind and generates fine but I can't figure out how to create an event handler for it.  I've found plenty of examples for it in C sharp, but none of them seem to apply to VB.  What I want to do is essentially this:

myDropDownList.SelectedIndexChanged = "Event to do here"

but it doesn't seem to work for me.

Any suggestions are appreciated.

Code in an event handler not working when used with system reflection.

Hi, I am presently writing an application that uses an MDI form with a ToolStrip on it. I have the need to build the menu items dynamically using an XML file. The format of the XML file is as follows: <ContextMenu EventHandlerHost="vFrmPDUsetup"> <!-- These styles will be applied to the menu items. Individual menu item styles can be override by defining as an attibute to the specific menu item, see below --> <Style> <MenuStripBackColour>Transparent</MenuStripBackColour> <BackColour></BackColour> <ForeColour>Chartreuse</ForeColour> <BackImage></BackImage> <!-- Must exist in Images folder --> <FontName>Tahoma</FontName> <FontSize>10</FontSize> <FontStyle>Bold</FontStyle> </Style> <!-- Attributes: Key = Resource Key name in resource file Image = image to display before text, image must exist in Images folder BackImage = background image, image must exist in Images folder BackColour = background colour as colour name ForeColour = foreground colour as colour name FontSize = size of font as value Seperator = add a menu seperator OnClick = click event pointing to the event handler method which must be defined as the MenuItem_ + <attibute value> &

Event Handler returning unexpected Error Code



I am trying to set up an Event Handler to log errors to a table.

So in my Control Flow pane I set an Execute SQL Task with a deliberate error as follows; -

Name; - Execute SQL Task with Deliberate Error

SQLStatement; - SELECT * FROM InvalidTable


Within the Event Handler tab I created a further Execute SQL Statement based on the Event handler OnError

Name : Log

Parameter Mapping
Variable Name System:ErrorCode
Direction Input
Parameter Name 0
Parameter Size 100

SQLStatement INSERT INTO dbo.CustomSSISLog  (ErrorCode) VALUES (?)

Error Output; -

SSIS package "ErrorLogTemplate.dtsx" starting.

Error: 0xC002F210 at Execute SQL Task with Deliberate Error, Execute SQL Task: Executing the query "SELECT * FROM InvalidTable" failed with the following error: "Invalid object name 'InvalidTable'.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Task failed: Execute SQL Task with Deliberate Error

Warning: 0x80019002 at ErrorLogTemplate: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of er

want to launch modal Popup from created User Event handler




I have a create user wizard on my page and in the event handler (Created User) I get extra information from the user

via textboxes within the aspx etc.


I then do a response.redirect to another page.

What I want to happen is this


When the CreatedUser Event is fired, I  want a Modal Popup to show up with a message Processing your registration.

once the registration code is processed it will close and the users get redirected.


On my ASPX I have the Modal PopUp and a Panel.

In the code behind in the handler I put ModalPop.show()


but this does not work.


thanks for any suggestions



InfoPath Workflow Task Form "Loading" event handler only being called after App Pool recycled.


I have a Workflow that is using an InfoPath task form.  In the "FormEvents_Loading" method event handler I have some code that needs to run each time the form is opened.   I recycle the App Pool and open the form the code runs perfectly, but if I close and try to re-open the form the code is not run at all.  I can then recycle the App Pool again and on the next load the code executes just fine.   The code that is supposed to be run is a very simple statement to set a field value, so I don't think it is interfering.

Does anyone know what this might be?


Event Handler Credentials


I made EH that checks out document when OOB Approval WF is finished successfully.

I want doc to be checked out by WF Initiator, but by default it is made by System Account.

How can i change Event Handler Account ?

Infopath button click event in custom workflow code.


Hi All,

I have designed the infopath form(Init) and integrated with my state machine workflow. i want to access button click event (designed in Infopath form) in my workflow code.

Can you help me.




Pre_Init event handler problem


Hi all my friends

   I have to masterpages for my home page.

1. The first is for the annonymous users which has the login controls. its name is General_Anonymous.master.

2. The second one is for the logged in users which has a logout button and it hasn't the login controls in it. its name is General_LoggedIn.master.

in my default.aspx page I wrote the following code

protected void Page_PreInit(object sender, EventArgs e)
            if (Session["SupId"] == null && Session["CustomerId"] == null)
                this.MasterPageFile = "~/Masters/General_Anonymous.master";
                this.MasterPageFile = "~/Masters/General_LoggedIn.master";

Sharing a file handler between managed and unmanaged code?

This is related to Interops, and sharing a file handler between a WPF UI and a native C++ DLL. I'm working on an application using MVVM as a guide. I want to use WPF for the UI, however it is a complex scientific application, which requires performance, and I am using C++ along with some GPU based code for all the modeling/processing. This is a Windows based app, no real network comm involved. I come across a challenge in terms of storing data. The data is multi-dimensional, and can be projected in many ways, while each projection can be processed/filtered in many ways too. I end up with a tree of data, with the raw data at the root and many branches. XML seems like an ideal way to store the information about this dataset, but as far as the raw data, it is not so convenient. I read about base64 encoding and the various binary-XML techniques, but see a major issue: the size of the converted data (150% of the raw) which in my case is huge (raw data is easily 200MBs+, and the multitude of projections can make it several 100's of MBs easily). There is the option of saving several files, but then it may become a nightmare for a user to 'transfer' files properly, so a one-file system seems best. I basically need to have the XML-like structure accessible to the UI, while the raw data needs to be accessed by the unmanaged code. So I was thinking I could concat

Event Handler & AD

My event handler is working fine until i add AD part. After this string it stops firing at all: DirectoryEntry dom = new DirectoryEntry(); I mean it compiles, deploys and doesnt react to anything ( Why ? PS VS2010, SP2010  

MVVM. Access TabControl->TabItems from ViewModel

Hi Folks,   Well, I just start to use MVVM, and I want to migrate functionality from my old non mvvm project to my new mvvm project.   The problem is the following one: In my old app (wizard application), I use tab control. And I have such things as States there. For this purpose I use StateMachine approach: My tab control looks like:   private void sm_StateChanged(State current, State previous, State next) { switch (current.Name) { case StatesNames.WELCOME_SCREEN_STATE_NAME: MainTabControl.SelectedIndex = 0; break; case StatesNames.SERVER_SUMMARY_SCREEN_STATE_NAME: MainTabControl.SelectedIndex = 1; preCertificationTabControl.SelectedIndex = 0; break; case StatesNames.SERVER_DEFINITION_SCREEN_STATE_NAME: MainTabControl.SelectedIndex = 1; preCertificationTabControl.SelectedIndex = 1; break; case StatesNames.UPGRADE_PRECERTIFICATION_SCREEN_STATE_NAME: MainTabControl.SelectedIndex = 1; preCertificationTabControl.SelectedIndex = 2; break; case StatesNames.PRECERTIFICATION_SCREEN_STATE_NAME: NavigationStateMachine.GetInstance().SwitchToNextState(); break; } } Well, as you can see, I need to access my tabControl to indicate states :( but it is not correct from

Infopath Changed Event code triggering in preview but not in web filler.

Hi there, I've written some code for a changed event hookup on a field in infopath 2010. The form is for submission to a sharepoint 2010 forms library. What the code does is fill in a specific value into a field depending on the selected value from a combo-box elsewhere on the form. When i preview this in Infopath 2010 it works perfectly but when i fill out the form through the web interface it simply does nothing. I've got another piece of code which executes on load and this works perfectly in both the preview and the web filler. What it does is just set the value of a field when the form loads. Here is the code, could someone tell me what i'm doing wrong? public void InternalStartup() { EventManager.XmlEvents["/my:myFields/my:service_level"].Changed += new XmlChangedEventHandler(service_level_Changed); EventManager.FormEvents.Loading += new LoadingEventHandler(FormEvents_Loading); } public void service_level_Changed(object sender, XmlEventArgs e) { // Write your code here to change the main data source. XPathNavigator xroot = MainDataSource.CreateNavigator(); XPathNavigator serviceLevel = xroot.SelectSingleNode("/my:myFields/my:service_level",NamespaceManager); XPathNavigator xest = xroot.SelectSingleNode("/my:myFields/my:est_cost", NamespaceManager); switch (serviceLevel.Value)

how to get values of list item being entered in ItemAdding event handler?

Hi,          i am trying to get the values being entered in a listitem in the ItemAdding eventhandler as follows, but it doesnt work. public override void ItemAdding(SPItemEventProperties properties)         {             base.ItemAdding(properties);             SPSite CurrentSite = new SPSite("http://mm-moss/np/");             SPWeb CurrentWeb = properties.OpenWeb();             SPList CurrentList = CurrentWeb.Lists[properties.ListId];             string vehicleNo = CurrentList.Items[CurrentList.Items.Count - 1]["Vehicle No"].ToString();             string  name=CurrentList.Items[CurrentList.Items.Count-1]["Name"].ToString(); } when i debug i cant get hold of the VehicleNo value. canyone help me in getting the values of the list item being entered? Thank you all.

Create a meeting instance with an event handler

Hi, i want to know if its posible to insert a new meeting instance in a meeting workspace automatically when you add a new event in a calendar.   i try to pass automatically the option of the template selection.   its posible with the objetc model or web services?   thanks

Event Binding in MVVM

We are implementing the MVVM in the WPF forms that we are designing. For this we have designed the specific ViewModels for each WPF view. The WPF form has various controls such as button, combo box etc. We are registering the button click event and other events in the ViewModel constructor. Is there better way of handling this? Pls.guide

Event handler that will take an e-mail sent to a doc library and save it as an .MSG file within the

Hi All, I have a requirement to create an event handler that will take an e-mail sent to a doc library and save it as an .MSG file within the library? Any help/inputs on getting this done is much appreciated.  Hanif
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend