.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

ViewModel PropertyChanged

Posted By:      Posted Date: September 14, 2010    Points: 0   Category :WPF
Hi all In my Viewmodel i have this property: BusinessAnagrafica _businessAnagrafica; public BusinessAnagrafica BusinessAnagrafica {     get     {         return _businessAnagrafica;     }     set     {         if (value != _businessAnagrafica)         {             if (_businessAnagrafica != null) _businessAnagrafica.AnagraficaModel.Recapito.PropertyChanged -= OnAnagraficaChanged;             _businessAnagrafica = value;             if (_businessAnagrafica != null)             {                 if (_businessAnagrafica != null) _businessAnagrafica.AnagraficaModel.Recapito.PropertyChanged += OnAnagraficaChanged;             }         }     } } in my View i have a textbox with this binding: Text="{Binding BusinessAnagrafica.AnagraficaModel.Recapito.TextRecapito, ValidatesOnDataErrors=True, UpdateSource

View Complete Post

More Related Resource Links

Dialogs and ViewModel - Using Tasks as a Pattern

The ViewModel/MVVM pattern continues to gain popularity, with a blog post showing up every so often, and with tweets and retweets popping up even more often :-). At the same time, there are some interesting topics beyond the core pattern that continue to fuel experimentation. A big one amongst those is how should applications use dialogs when using the view model pattern.

The crux of the problem is the desire to keep the view model independent of UI concerns, and ensure it can be tested in a standalone manner, but that often comes to odds when you want the view model to launch a dialog, and/or do some work after the dialog is closed.

A Generic Dialog ViewModel

I worked on a wpf viewmodel for dialogs, because it seemed strange to me that you needed for instance windows forms dialogs to open or save files in wpf. So I set about creating my own wpf dialogs. After creating the dialog viewmodels there still remained a small issue with the library and also I didn't have much time to write an article about it. I however published the library containing the viewmodels for dialogs with another article on my blog

Design Patterns: Problems and Solutions with Model-View-ViewModel


The Model-View-ViewModel (MVVM) design pattern describes a popular approach for building Windows Presentation Foundation or Microsoft Silverlight applications. Robert McCarter shows you how the ViewModel works, and discuss some benefits and issues involved in implementing a ViewModel in your code.

Robert McCarter

MSDN Magazine July 2010

Silverlight Patterns: Model-View-ViewModel In Silverlight 2 Apps


In this article, you'll learn how to avoid problematic tight coupling by applying the Model-View-ViewModel pattern in Silverlight 2.

Shawn Wildermuth

MSDN Magazine March 2009

Patterns: WPF Apps With The Model-View-ViewModel Design Pattern


In this article we explain just how simple it can be to build a WPF application the right way using the MVVM Pattern.

Josh Smith

MSDN Magazine February 2009

MVC3: Define Dynamic ViewModel property inside Action Filter



How can I define a Dynamic ViewModel property in MVC 3 inside an action filter?

I am looking to have something like but inside the ActionFilter and not in the controller:

ViewModel.Title = "Home";

Thank You,


Viewmodel property not set to [Required] yet getting error message saying it is?


I have a viewmodel that i use for my view

public int SelectionId{ get; set; }        
public IEnumerable<Selections> Selections { get; set; }

Notice that SelectionId is not decorated with [Required]. In my view, i use DropDownFor like this:

<%= Html.DropDownListFor(m => m.SelectionId, new SelectList(Model.Selections, "Id", "Name"), "--- Select ---")%>

It should be possible to not select anything from the dropdown, resulting in model.SelectionId = 0, which is fine. Why do i get a "SelectionId field is required" error when i Post?  If i do this:

<%= Html.DropDownList(mySelectionId, new SelectList(Model.Selections, "Id", "Name"), "--- Select ---")%>

I no longer get the error if i dont select anything, which is what i want - but no way to bind it to the id if the user does select something

thanks for any help!

PropertyChangedEventHandler handler = this.PropertyChanged;

Ah yes the INotifyProperty interface defines the event in title of this post.   A well known pattern often is seen on the internet in using this Interface.  Josh Smith includes this pattern in his ViewModelAbstractBase class as shown here: Implementation of INotifyProperyChanged in ViewModel Abstract Base Class     #region INotifyPropertyChanged Members         /// <summary>         /// Raised when a property on this object has a new value.         /// </summary>         public event PropertyChangedEventHandler PropertyChanged;         /// <summary>         /// Raises this object's PropertyChanged event.         /// </summary>         /// <param name="propertyName">The property that has a new value.</param>         protected virtual void

XAML - ValueConverter Parameters and PropertyChanged callback

Hi I am trying to use a IValueConverter on the flowdocument of a richtextbox. However, ideally I'd like to be able to inject some dependencies into the converter on construction or perhaps with a setter of some sort. Previously I've been using an IoC to construct a formatter-type object and can obviously specify the constructor dependency quite easily. However, I was hoping to use XAML and the IValueConverter as much as possible, but specifying the converter in the Grid.Resources requires a parameterless constructor. Are there other ways in which I can do this or do I need to think about the problem differently. In addition, because you cannot bind to a RichTextBox, I have introduced an AttachedProperty. Here's some code     Public Shared ReadOnly DocumentProperty As DependencyProperty = DependencyProperty.RegisterAttached("Document", GetType(FlowDocument), GetType(RichTextBoxExtensions), RichTextBoxFrameworkPropertyMetaData) Private Shared Function RichTextBoxFrameworkPropertyMetaData() As FrameworkPropertyMetadata Dim metaData = New FrameworkPropertyMetadata metaData.BindsTwoWayByDefault = True metaData.AffectsRender = True metaData.PropertyChangedCallback = New PropertyChangedCallback(Sub(obj, e) If _recursionProtection.Contains(Thread.CurrentThread) Then Return Dim rtb = CType

How to raise RoutedEvent in ViewModel?

In my UserControl.xaml - Update Button: binding to VM UpdateCommand      <Button Width="Auto" Height="24" Margin= "5" HorizontalAlignment="Right"             Command="{Binding Path=UpdateCommand}" /> in UserControl.xaml.cs - RountedEvent: UpdateClickEvent         public static readonly RoutedEvent UpdateClickEvent =             EventManager.RegisterRoutedEvent(            "UpdateClick", RoutingStrategy.Bubble,             typeof(RoutedEventHandler),             typeof(UserControl));         public event RoutedEventHandler UpdateClick        {            add { AddHandler(UpdateClickEvent, value); }            remove { RemoveHandler(Updat

Custom mapping from formValues to ViewModel

Let's say i have simple ViewModel : class SimpleViewModel { public string prop1 {get;set;} public string prop2 {get;set;} } And I have following markup:<input type="text" id="prop1input" /><input type="text" id="prop2input" />I am wondering is it possible to make custom mapping from form values submitted via POST to model values, something like this:class SimpleViewModel { [HttpMappingAttr("prop1input")] public string prop1 {get;set;} [HttpMappingAttr("prop2input")] public string prop2 {get;set;} }

The model of type could not be updated viewModel

Hello,  Ok i am pritty sure this is because I dont know how to handle sending back my viewmodel on edit:Error I am dealing with:here is my [HttpGet] public ActionResult Edit(int id) { ItemEditViewModel ItemEditVM = new ItemEditViewModel(); ItemEditVM.product = storedb.Products.Single(a => a.Product_Key == id); TempData["Error"] = ""; return View(ItemEditVM); } Form is nothing specials standard strongly typed using the view model [HttpPost] public ActionResult Edit(int id, FormCollection collection) { var product = storedb.Products.Single(a => a.Product_Key == id); try { UpdateModel(product, "product"); <--- Errors Here storedb.SaveChanges();//myview model i am usingpublic class ItemEditViewModel    {        public Product product {get; set;}    } Thanks  

PropertyOf and INotifyPropertyChanged.PropertyChanged without strings

When coding applications using design patterns such as MVP (Model-View-Presenter) or MVVM (Model-View-ViewModel), you'll find yourself using data binding and the INotifyPropertyChanged interface all over the place. This means referencing properties quite a lot. For example, when you want to notify that the value of a property has changed, you can write NotifyPropertyChange("SomeProperty") where NotifyPropertyChange is a method that invokes the INotifyPropertyChanged.PropertyChanged event. The major inconvenience of using a string to reference a property name, as in NotifyPropertyChange("SomeProperty"), is that it's a very brittle approach. If the name of the property changes or the property is removed during some refactoring operation on the source code, then it's easy to forget to update all the "string references". Luckily, solutions exist to avoid this kind of issues. infoof => PropertyOf, FieldOf, MethodOf, ConstructorOf We don't have propertyof or infoof operators in C# (see 1, 2, 3 or 4), but we can use things such as PropertyOf thanks to expression trees. You can learn more about such an approach on the C# FAQ blog and Patrick Smacchia's blog. Here is the source code, derived from the above articles, that I use in a utility class: Snippet public static MethodInfo MethodOf<T>(Expression<Func<T>> expression){  var&

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

Binding WPF grid to ViewModel : Suggest the design

I have structure like this I have following structure BaseViewModel ViewModel1: BaseviewModel ViewModel2: BaseViewModel In grid i will be showing the data from both the ViewModel1 and ViewModel2 (some common data is there ) How should i go about this Expected functionality : IF i select any row in the grid i should get respective ViewModel    

Updating ViewModel values on HttpPost

Hi there, I am just getting started with MVC after many years of WebForms development. I am struggling with some basics that I hope you can help out with. I have a very simple page with two textbox fields, one called Input where a user will enter something, and one called Output where I want to return some string after they post the form, much like a postback scenario in WebForms. I have the View connected to a ViewModel for strong typing. The ViewModel: public class TestViewModel { public string Input { get; set; } public string Output { get; set; } } The View: <% Html.BeginForm(); %> <%: Html.TextBoxFor(x => x.Input) %> <input type="submit" value="Submit" /> <br /><br /> <%: Html.TextAreaFor(x => x.Output)%> <% Html.EndForm(); %>   The Controller: public ActionResult Test() { var viewModel = new TestViewModel(); viewModel.Input = "Enter something"; return View("Test",viewModel); } [HttpPost] public ActionResult Test(TestViewModel viewModel) { viewModel.Output = "Here is some response"; return View("Test", viewModel); } The problem I have is that the

MVC2 NerdDinner - Data no longer saves after adding ViewModel

I am writing this post to document some issues I ran into, and hopefully help anybody else who gets stuck in the same place.  I am creating the NerdDinner application via the Professional ASP.NET MVC 2 book,  and once I got to the ViewModel part (pages 88-91), I noticed none of my data was saving any longer.  I discovered several errors and areas of confusion in these pages of the book, which I will list now. Page 88:  When it says to add the DinnerFormViewModel class, it doesn't say what folder to add it to.  On page 89, the Inherits example (NerdDinner.Controllers.DinnerFormViewModel) implies it was added to the Controllers folder, but if that were so, the code on page 88 would need to use Models.Dinner instead of just Dinner.  No big deal; just put it in Models and change the Inherit statement on page 89 to use NerdDinner.Models.DinnerFormViewModel. Page 89:  At the bottom of the page is some wrong code.  Since the properties of Dinner are now one level deeper, all references to m.Title, m.Country, etc, need to be m.Dinner.Title, m.Dinner.Country, etc.  The statements above the code are also incorrect ("Notice... we are not changing the names of the input elements... the form elements will still be named...") -- the form elements will actually change from "Title", "Country&quo
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