Search Results

Search found 253 results on 11 pages for 'inotifypropertychanged'.

Page 3/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Is it getting to be time for C# to support compile-time macros?

    - by Robert Rossney
    Thus far, Microsoft's C# team has resisted adding formal compile-time macro capabilities to the language. There are aspects of programming with WPF that seem (to me, at least) to be creating some compelling use cases for macros. Dependency properties, for instance. It would be so nice to just be able to do something like this: [DependencyProperty] public string Foo { get; set; } and have the body of the Foo property and the static FooProperty property be generated automatically at compile time. Or, for another example an attribute like this: [NotifyPropertyChanged] public string Foo { get; set; } that would make the currently-nonexistent preprocessor produce this: private string _Foo; public string Foo { get { return _Foo; } set { _Foo = value; OnPropertyChanged("Foo"); } } You can implement change notification with PostSharp, and really, maybe PostSharp is a better answer to the question. I really don't know. Assuming that you've thought about this more than I have, which if you've thought about it at all you probably have, what do you think? (This is clearly a community wiki question and I've marked it accordingly.)

    Read the article

  • Firing PropertyChanged event in a complex, nested type in WPF

    - by John
    Hey I have a question about the PropertyChanged vent firing in WPF whne it is used in a complex type. I have a class called DataStore and a list of Departments (an ObservableCollection), and each department again has a list of Products. Properties in the Product class that are changed also affect properties in the Department and DataStore class. How does each Product notify the Department it belongs to, and the DataStore (which is the mother class of all) that one or more of its properties have changed their values? Example: a product has a property NumberSoldToday and is bound. The Department has a property called TotalNumberOfProductsSold: public int TotalNumberOfProductsSold { get { int result = 0; foreach(Product p in this.products) result += p.NumberSoldToday; return result; } } And the data store has a property TotalProductsSold (for all departments): public int TotalProductsSold { get { int result = 0; foreach(Product p in this.deparments) result += p.TotalNumberOfProductsSold; return result; } } If all these properties are bound, and the innermost property changes, it must somehow notify that the value of the other 2 changed as well. How? The only way I can see this happening is to hook up the PropertyChanged event in each class. Th event must also fire when deleting, adding to the collection of products and deparments, respectively. Is there a better, more clever way to do this?

    Read the article

  • Shawn Wildermuth violating MVVM in MSDN article?

    - by rasx
    This may be old news but back in March 2009, Shawn Wildermuth, his article, “Model-View-ViewModel In Silverlight 2 Apps,” has a code sample that includes DataServiceEntityBase: // COPIED FROM SILVERLIGHTCONTRIB Project for simplicity /// <summary> /// Base class for DataService Data Contract classes to implement /// base functionality that is needed like INotifyPropertyChanged. /// Add the base class in the partial class to add the implementation. /// </summary> public abstract class DataServiceEntityBase : INotifyPropertyChanged { /// <summary> /// The handler for the registrants of the interface's event /// </summary> PropertyChangedEventHandler _propertyChangedHandler; /// <summary> /// Allow inheritors to fire the event more simply. /// </summary> /// <param name="propertyName"></param> protected void FirePropertyChanged(string propertyName) { if (_propertyChangedHandler != null) { _propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName)); } } #region INotifyPropertyChanged Members /// <summary> /// The interface used to notify changes on the entity. /// </summary> event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _propertyChangedHandler += value; } remove { _propertyChangedHandler -= value; } } #endregion What this class implies is that the developer intends to bind visuals directly to data (yes, a ViewModel is used but it defines an ObservableCollection of data objects). Is this design diverging too far from the guidance of MVVM? Now I can see some of the reasons why Shawn would go this way: what Shawn can do with DataServiceEntityBase is this sort of thing (which is intimate with the Entity Framework): // Partial Method to support the INotifyPropertyChanged interface public partial class Game : DataServiceEntityBase { #region Partial Method INotifyPropertyChanged Implementation // Override the Changed partial methods to implement the // INotifyPropertyChanged interface // This helps with the Model implementation to be a mostly // DataBound implementation partial void OnDeveloperChanged() { base.FirePropertyChanged("Developer"); } partial void OnGenreChanged() { base.FirePropertyChanged("Genre"); } partial void OnListPriceChanged() { base.FirePropertyChanged("ListPrice"); } partial void OnListPriceCurrencyChanged() { base.FirePropertyChanged("ListPriceCurrency"); } partial void OnPlayerInfoChanged() { base.FirePropertyChanged("PlayerInfo"); } partial void OnProductDescriptionChanged() { base.FirePropertyChanged("ProductDescription"); } partial void OnProductIDChanged() { base.FirePropertyChanged("ProductID"); } partial void OnProductImageUrlChanged() { base.FirePropertyChanged("ProductImageUrl"); } partial void OnProductNameChanged() { base.FirePropertyChanged("ProductName"); } partial void OnProductTypeIDChanged() { base.FirePropertyChanged("ProductTypeID"); } partial void OnPublisherChanged() { base.FirePropertyChanged("Publisher"); } partial void OnRatingChanged() { base.FirePropertyChanged("Rating"); } partial void OnRatingUrlChanged() { base.FirePropertyChanged("RatingUrl"); } partial void OnReleaseDateChanged() { base.FirePropertyChanged("ReleaseDate"); } partial void OnSystemNameChanged() { base.FirePropertyChanged("SystemName"); } #endregion } Of course MSDN code can seen as “toy code” for educational purposes but is anyone doing anything like this in the real world of Silverlight development?

    Read the article

  • Does this MSDN article violate MVVM?

    - by rasx
    This may be old news but back in March 2009, this article, “Model-View-ViewModel In Silverlight 2 Apps,” has a code sample that includes DataServiceEntityBase: // COPIED FROM SILVERLIGHTCONTRIB Project for simplicity /// <summary> /// Base class for DataService Data Contract classes to implement /// base functionality that is needed like INotifyPropertyChanged. /// Add the base class in the partial class to add the implementation. /// </summary> public abstract class DataServiceEntityBase : INotifyPropertyChanged { /// <summary> /// The handler for the registrants of the interface's event /// </summary> PropertyChangedEventHandler _propertyChangedHandler; /// <summary> /// Allow inheritors to fire the event more simply. /// </summary> /// <param name="propertyName"></param> protected void FirePropertyChanged(string propertyName) { if (_propertyChangedHandler != null) { _propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName)); } } #region INotifyPropertyChanged Members /// <summary> /// The interface used to notify changes on the entity. /// </summary> event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _propertyChangedHandler += value; } remove { _propertyChangedHandler -= value; } } #endregion What this class implies is that the developer intends to bind visuals directly to data (yes, a ViewModel is used but it defines an ObservableCollection of data objects). Is this design diverging too far from the guidance of MVVM? Now I can see some of the reasons Why would we go this way: what we can do with DataServiceEntityBase is this sort of thing (which is intimate with the Entity Framework): // Partial Method to support the INotifyPropertyChanged interface public partial class Game : DataServiceEntityBase { #region Partial Method INotifyPropertyChanged Implementation // Override the Changed partial methods to implement the // INotifyPropertyChanged interface // This helps with the Model implementation to be a mostly // DataBound implementation partial void OnDeveloperChanged() { base.FirePropertyChanged("Developer"); } partial void OnGenreChanged() { base.FirePropertyChanged("Genre"); } partial void OnListPriceChanged() { base.FirePropertyChanged("ListPrice"); } partial void OnListPriceCurrencyChanged() { base.FirePropertyChanged("ListPriceCurrency"); } partial void OnPlayerInfoChanged() { base.FirePropertyChanged("PlayerInfo"); } partial void OnProductDescriptionChanged() { base.FirePropertyChanged("ProductDescription"); } partial void OnProductIDChanged() { base.FirePropertyChanged("ProductID"); } partial void OnProductImageUrlChanged() { base.FirePropertyChanged("ProductImageUrl"); } partial void OnProductNameChanged() { base.FirePropertyChanged("ProductName"); } partial void OnProductTypeIDChanged() { base.FirePropertyChanged("ProductTypeID"); } partial void OnPublisherChanged() { base.FirePropertyChanged("Publisher"); } partial void OnRatingChanged() { base.FirePropertyChanged("Rating"); } partial void OnRatingUrlChanged() { base.FirePropertyChanged("RatingUrl"); } partial void OnReleaseDateChanged() { base.FirePropertyChanged("ReleaseDate"); } partial void OnSystemNameChanged() { base.FirePropertyChanged("SystemName"); } #endregion } Of course MSDN code can seen as “toy code” for educational purposes but is anyone doing anything like this in the real world of Silverlight development?

    Read the article

  • Implementing an Interceptor Using NHibernate’s Built In Dynamic Proxy Generator

    - by Ricardo Peres
    NHibernate 3.2 came with an included proxy generator, which means there is no longer the need – or the possibility, for that matter – to choose Castle DynamicProxy, LinFu or Spring. This is actually a good thing, because it means one less assembly to deploy. Apparently, this generator was based, at least partially, on LinFu. As there are not many tutorials out there demonstrating it’s usage, here’s one, for demonstrating one of the most requested features: implementing INotifyPropertyChanged. This interceptor, of course, will still feature all of NHibernate’s functionalities that you are used to, such as lazy loading, and such. We will start by implementing an NHibernate interceptor, by inheriting from the base class NHibernate.EmptyInterceptor. This class does not do anything by itself, but it allows us to plug in behavior by overriding some of its methods, in this case, Instantiate: 1: public class NotifyPropertyChangedInterceptor : EmptyInterceptor 2: { 3: private ISession session = null; 4:  5: private static readonly ProxyFactory factory = new ProxyFactory(); 6:  7: public override void SetSession(ISession session) 8: { 9: this.session = session; 10: base.SetSession(session); 11: } 12:  13: public override Object Instantiate(String clazz, EntityMode entityMode, Object id) 14: { 15: Type entityType = Type.GetType(clazz); 16: IProxy proxy = factory.CreateProxy(entityType, new _NotifyPropertyChangedInterceptor(), typeof(INotifyPropertyChanged)) as IProxy; 17: 18: _NotifyPropertyChangedInterceptor interceptor = proxy.Interceptor as _NotifyPropertyChangedInterceptor; 19: interceptor.Proxy = this.session.SessionFactory.GetClassMetadata(entityType).Instantiate(id, entityMode); 20:  21: this.session.SessionFactory.GetClassMetadata(entityType).SetIdentifier(proxy, id, entityMode); 22:  23: return (proxy); 24: } 25: } Then we need a class that implements the NHibernate dynamic proxy behavior, let’s place it inside our interceptor, because it will only need to be used there: 1: class _NotifyPropertyChangedInterceptor : NHibernate.Proxy.DynamicProxy.IInterceptor 2: { 3: private PropertyChangedEventHandler changed = delegate { }; 4:  5: public Object Proxy 6: { 7: get; 8: set;} 9:  10: #region IInterceptor Members 11:  12: public Object Intercept(InvocationInfo info) 13: { 14: Boolean isSetter = info.TargetMethod.Name.StartsWith("set_") == true; 15: Object result = null; 16:  17: if (info.TargetMethod.Name == "add_PropertyChanged") 18: { 19: PropertyChangedEventHandler propertyChangedEventHandler = info.Arguments[0] as PropertyChangedEventHandler; 20: this.changed += propertyChangedEventHandler; 21: } 22: else if (info.TargetMethod.Name == "remove_PropertyChanged") 23: { 24: PropertyChangedEventHandler propertyChangedEventHandler = info.Arguments[0] as PropertyChangedEventHandler; 25: this.changed -= propertyChangedEventHandler; 26: } 27: else 28: { 29: result = info.TargetMethod.Invoke(this.Proxy, info.Arguments); 30: } 31:  32: if (isSetter == true) 33: { 34: String propertyName = info.TargetMethod.Name.Substring("set_".Length); 35: this.changed(this.Proxy, new PropertyChangedEventArgs(propertyName)); 36: } 37:  38: return (result); 39: } 40:  41: #endregion 42: } What this does for every interceptable method (those who are either virtual or from the INotifyPropertyChanged) is: For methods that came from the INotifyPropertyChanged interface, add_PropertyChanged and remove_PropertyChanged (yes, events are methods ), we add an implementation that adds or removes the event handlers to the delegate which we declared as changed; For all the others, we direct them to the place where they are actually implemented, which is the Proxy field; If the call is setting a property, it fires afterwards the PropertyChanged event. In order to use this, we need to add the interceptor to the Configuration before building the ISessionFactory: 1: using (ISessionFactory factory = cfg.SetInterceptor(new NotifyPropertyChangedInterceptor()).BuildSessionFactory()) 2: { 3: using (ISession session = factory.OpenSession()) 4: using (ITransaction tx = session.BeginTransaction()) 5: { 6: Customer customer = session.Get<Customer>(100); //some id 7: INotifyPropertyChanged inpc = customer as INotifyPropertyChanged; 8: inpc.PropertyChanged += delegate(Object sender, PropertyChangedEventArgs e) 9: { 10: //fired when a property changes 11: }; 12: customer.Address = "some other address"; //will raise PropertyChanged 13: customer.RecentOrders.ToList(); //will trigger the lazy loading 14: } 15: } Any problems, questions, do drop me a line!

    Read the article

  • design a model for a system of dependent variables

    - by dbaseman
    I'm dealing with a modeling system (financial) that has dozens of variables. Some of the variables are independent, and function as inputs to the system; most of them are calculated from other variables (independent and calculated) in the system. What I'm looking for is a clean, elegant way to: define the function of each dependent variable in the system trigger a re-calculation, whenever a variable changes, of the variables that depend on it A naive way to do this would be to write a single class that implements INotifyPropertyChanged, and uses a massive case statement that lists out all the variable names x1, x2, ... xn on which others depend, and, whenever a variable xi changes, triggers a recalculation of each of that variable's dependencies. I feel that this naive approach is flawed, and that there must be a cleaner way. I started down the path of defining a CalculationManager<TModel> class, which would be used (in a simple example) something like as follows: public class Model : INotifyPropertyChanged { private CalculationManager<Model> _calculationManager = new CalculationManager<Model>(); // each setter triggers a "PropertyChanged" event public double? Height { get; set; } public double? Weight { get; set; } public double? BMI { get; set; } public Model() { _calculationManager.DefineDependency<double?>( forProperty: model => model.BMI, usingCalculation: (height, weight) => weight / Math.Pow(height, 2), withInputs: model => model.Height, model.Weight); } // INotifyPropertyChanged implementation here } I won't reproduce CalculationManager<TModel> here, but the basic idea is that it sets up a dependency map, listens for PropertyChanged events, and updates dependent properties as needed. I still feel that I'm missing something major here, and that this isn't the right approach: the (mis)use of INotifyPropertyChanged seems to me like a code smell the withInputs parameter is defined as params Expression<Func<TModel, T>>[] args, which means that the argument list of usingCalculation is not checked at compile time the argument list (weight, height) is redundantly defined in both usingCalculation and withInputs I am sure that this kind of system of dependent variables must be common in computational mathematics, physics, finance, and other fields. Does someone know of an established set of ideas that deal with what I'm grasping at here? Would this be a suitable application for a functional language like F#? Edit More context: The model currently exists in an Excel spreadsheet, and is being migrated to a C# application. It is run on-demand, and the variables can be modified by the user from the application's UI. Its purpose is to retrieve variables that the business is interested in, given current inputs from the markets, and model parameters set by the business.

    Read the article

  • idiomatic property changed notification in scala?

    - by Jeremy Bell
    I'm trying to find a cleaner alternative (that is idiomatic to Scala) to the kind of thing you see with data-binding in WPF/silverlight data-binding - that is, implementing INotifyPropertyChanged. First, some background: In .Net WPF or silverlight applications, you have the concept of two-way data-binding (that is, binding the value of some element of the UI to a .net property of the DataContext in such a way that changes to the UI element affect the property, and vise versa. One way to enable this is to implement the INotifyPropertyChanged interface in your DataContext. Unfortunately, this introduces a lot of boilerplate code for any property you add to the "ModelView" type. Here is how it might look in Scala: trait IDrawable extends INotifyPropertyChanged { protected var drawOrder : Int = 0 def DrawOrder : Int = drawOrder def DrawOrder_=(value : Int) { if(drawOrder != value) { drawOrder = value OnPropertyChanged("DrawOrder") } } protected var visible : Boolean = true def Visible : Boolean = visible def Visible_=(value: Boolean) = { if(visible != value) { visible = value OnPropertyChanged("Visible") } } def Mutate() : Unit = { if(Visible) { DrawOrder += 1 // Should trigger the PropertyChanged "Event" of INotifyPropertyChanged trait } } } For the sake of space, let's assume the INotifyPropertyChanged type is a trait that manages a list of callbacks of type (AnyRef, String) = Unit, and that OnPropertyChanged is a method that invokes all those callbacks, passing "this" as the AnyRef, and the passed-in String). This would just be an event in C#. You can immediately see the problem: that's a ton of boilerplate code for just two properties. I've always wanted to write something like this instead: trait IDrawable { val Visible = new ObservableProperty[Boolean]('Visible, true) val DrawOrder = new ObservableProperty[Int]('DrawOrder, 0) def Mutate() : Unit = { if(Visible) { DrawOrder += 1 // Should trigger the PropertyChanged "Event" of ObservableProperty class } } } I know that I can easily write it like this, if ObservableProperty[T] has Value/Value_= methods (this is the method I'm using now): trait IDrawable { // on a side note, is there some way to get a Symbol representing the Visible field // on the following line, instead of hard-coding it in the ObservableProperty // constructor? val Visible = new ObservableProperty[Boolean]('Visible, true) val DrawOrder = new ObservableProperty[Int]('DrawOrder, 0) def Mutate() : Unit = { if(Visible.Value) { DrawOrder.Value += 1 } } } // given this implementation of ObservableProperty[T] in my library // note: IEvent, Event, and EventArgs are classes in my library for // handling lists of callbacks - they work similarly to events in C# class PropertyChangedEventArgs(val PropertyName: Symbol) extends EventArgs("") class ObservableProperty[T](val PropertyName: Symbol, private var value: T) { protected val propertyChanged = new Event[PropertyChangedEventArgs] def PropertyChanged: IEvent[PropertyChangedEventArgs] = propertyChanged def Value = value; def Value_=(value: T) { if(this.value != value) { this.value = value propertyChanged(this, new PropertyChangedEventArgs(PropertyName)) } } } But is there any way to implement the first version using implicits or some other feature/idiom of Scala to make ObservableProperty instances function as if they were regular "properties" in scala, without needing to call the Value methods? The only other thing I can think of is something like this, which is more verbose than either of the above two versions, but is still less verbose than the original: trait IDrawable { private val visible = new ObservableProperty[Boolean]('Visible, false) def Visible = visible.Value def Visible_=(value: Boolean): Unit = { visible.Value = value } private val drawOrder = new ObservableProperty[Int]('DrawOrder, 0) def DrawOrder = drawOrder.Value def DrawOrder_=(value: Int): Unit = { drawOrder.Value = value } def Mutate() : Unit = { if(Visible) { DrawOrder += 1 } } }

    Read the article

  • MVVM Light Toolkit - RelayCommands, DelegateCommands, and ObservableObjects

    - by DanM
    I just started experimenting with Laurent Bugnion's MVVM Light Toolkit. I think I'm going to really like it, but I have a couple questions. Before I get to them, I need to explain where I'm coming from. I currently use a combination of Josh Smith's MVVM Foundation and another project on Codeplex called MVVM Toolkit. I use ObservableObject and Messenger from MVVM Foundation and DelegateCommand and CommandReference from MVVM Toolkit. The only real overlap between MVVM Foundation and MVVM Tookit is that they both have an implementation for ICommand: MVVM Foundation has a RelayCommand and MVVM Tookit has a DelegateCommand. Of these two, DelegateCommand appears to be more sophisticated. It employs a CommandManagerHelper that uses weak references to avoid memory leaks. With that said, a couple questions: Why does MVVM Light Toolkit use RelayCommand rather than DelegateCommand? Is the use of weak references in an ICommand unnecessary or not recommended for some reason? Why is there no ObservableObject in MVVM Light? ObservableObject is basically just the part of ViewModelBase that implements INotifyPropertyChanged, but it's very convenient to have as a separate class because view-models are not the only objects that need to implement INotifyPropertyChanged. For example, let's say you have DataGrid that binds to a list of Person objects. If any of the properties in Person can change while the user is viewing the DataGrid, Person would need to implement INotifyPropertyChanged. (I realize that if Person is auto-generated using something like LinqToSql, it will probably already implement INotifyPropertyChanged, but there are cases where I need to make a view-specific version of entity model objects, say, because I need to include a command to support a button column in a DataGrid.) Thanks.

    Read the article

  • group dynamic data from a List

    - by prince23
    public class SampleProjectData { public static ObservableCollection<Product> GetSampleData() { DateTime dtS = DateTime.Now; ObservableCollection<Product> teams = new ObservableCollection<Product>(); teams.Add(new Product() { PDName = "Product1", OverallStartTime = dtS, OverallEndTime = dtS + TimeSpan.FromDays(3), }); Project emp = new Project() { PName = "Project1", OverallStartTime = dtS + TimeSpan.FromDays(1), OverallEndTime = dtS + TimeSpan.FromDays(6) }; emp.Tasks.Add(new Task() { StartTime = dtS, EndTime = dtS + TimeSpan.FromDays(2), TaskName = "John's Task 3" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(3), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "John's Task 2" }); teams[0].Projects.Add(emp); emp = new Project() { PName = "Project2", OverallStartTime = dtS + TimeSpan.FromDays(1.5), OverallEndTime = dtS + TimeSpan.FromDays(5.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Victor's Task" }); teams[0].Projects.Add(emp); emp = new Project() { PName = "Project3", OverallStartTime = dtS + TimeSpan.FromDays(2), OverallEndTime = dtS + TimeSpan.FromDays(5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Jason's Task 1" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(7), EndTime = dtS + TimeSpan.FromDays(9), TaskName = "Jason's Task 2" }); teams[0].Projects.Add(emp); teams.Add(new Product() { PDName = "Product2", OverallStartTime = dtS, OverallEndTime = dtS + TimeSpan.FromDays(3) }); emp = new Project() { PName = "Project4", OverallStartTime = dtS + TimeSpan.FromDays(0.5), OverallEndTime = dtS + TimeSpan.FromDays(3.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1.5), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Vicky's Task" }); teams[1].Projects.Add(emp); emp = new Project() { PName = "Project5", OverallStartTime = dtS + TimeSpan.FromDays(2), OverallEndTime = dtS + TimeSpan.FromDays(6) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(2.2), EndTime = dtS + TimeSpan.FromDays(3.8), TaskName = "Oleg's Task 1" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(5), EndTime = dtS + TimeSpan.FromDays(6), TaskName = "Oleg's Task 2" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(8), EndTime = dtS + TimeSpan.FromDays(9.6), TaskName = "Oleg's Task 3" }); teams[1].Projects.Add(emp); emp = new Project() { PName = "Project6", OverallStartTime = dtS + TimeSpan.FromDays(2.5), OverallEndTime = dtS + TimeSpan.FromDays(4.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(0.8), EndTime = dtS + TimeSpan.FromDays(2), TaskName = "Kim's Task" }); teams[1].Projects.Add(emp); teams.Add(new Product() { PDName = "Product3", OverallStartTime = dtS, OverallEndTime = dtS + TimeSpan.FromDays(3) }); emp = new Project() { PName = "Project7", OverallStartTime = dtS + TimeSpan.FromDays(5), OverallEndTime = dtS + TimeSpan.FromDays(7.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1.5), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Balaji's Task 1" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(5), EndTime = dtS + TimeSpan.FromDays(8), TaskName = "Balaji's Task 2" }); teams[2].Projects.Add(emp); emp = new Project() { PName = "Project8", OverallStartTime = dtS + TimeSpan.FromDays(3), OverallEndTime = dtS + TimeSpan.FromDays(6.3) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1.75), EndTime = dtS + TimeSpan.FromDays(2.25), TaskName = "Li's Task" }); teams[2].Projects.Add(emp); emp = new Project() { PName = "Project9", OverallStartTime = dtS + TimeSpan.FromDays(2), OverallEndTime = dtS + TimeSpan.FromDays(6) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(2), EndTime = dtS + TimeSpan.FromDays(3), TaskName = "Stacy's Task" }); teams[2].Projects.Add(emp); return teams; } } above is an sample data where i am grouping them with static data in the same way i need to for teh data which is cmg from DB and i need to store them list all these three data are comig from different services. and i am storing them in a list now i have three tables data Product , Project, Task. all the data are coming from webservies. i have created three list where i am storing the data in list. Listobjpro= new List(); Listobjproduct= new List(); LIstobjTask= new List(); now what i need to do is i need to do the mapping between these tables. if you see above. i have object of Product under Product i have added object of Project and then under project object i have added task object. now from the above data which is stored in the list i need to do the same mapping between class. and group the data. public class Product : INotifyPropertyChanged { public Product() { this.Projects = new ObservableCollection<Project>(); } public string PDName { get; set; } public ObservableCollection<Project> Projects { get; set; } private DateTime _st; public DateTime OverallStartTime { get { return _st; } set { if (this._st != value) { TimeSpan dur = this._et - this._st; this._st = value; this.OnPropertyChanged("OverallStartTime"); this.OverallEndTime = value + dur; } } } private DateTime _et; public DateTime OverallEndTime { get { return _et; } set { if (this._et != value) { this._et = value; this.OnPropertyChanged("OverallEndTime"); } } } #region INotifyPropertyChanged Members protected void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } public class Project : INotifyPropertyChanged { public Project() { this.Tasks = new ObservableCollection<Task>(); } public string PName { get; set; } public ObservableCollection<Task> Tasks { get; set; } DateTime _st; public DateTime OverallStartTime { get { return _st; } set { if (this._st != value) { TimeSpan dur = this._et - this._st; this._st = value; this.OnPropertyChanged("OverallStartTime"); this.OverallEndTime = value + dur; } } } DateTime _et; public DateTime OverallEndTime { get { return _et; } set { if (this._et != value) { this._et = value; this.OnPropertyChanged("OverallEndTime"); } } } #region INotifyPropertyChanged Members protected void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } public class Task : INotifyPropertyChanged { public string TaskName { get; set; } DateTime _st; public DateTime StartTime { get { return _st; } set { if (this._st != value) { TimeSpan dur = this._et - this._st; this._st = value; this.OnPropertyChanged("StartTime"); this.EndTime = value + dur; } } } private DateTime _et; public DateTime EndTime { get { return _et; } set { if (this._et != value) { this._et = value; this.OnPropertyChanged("EndTime"); } } } #region INotifyPropertyChanged Members protected void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; #endregion }

    Read the article

  • How do you raise a .Net event from an IronRuby class?

    - by Brian Genisio
    I'm trying to figure out how to implement an event in a ruby class. Specifically, I am trying to make my class implement an interface (INotifyPropertyChanged) that includes an event (PropertyChanged). I can create my add_PropertyChanged and remove_PropertyChanged methods... but then what? This is what my class looks like so far: class TestClass include System::ComponentModel::INotifyPropertyChanged def add_PropertyChanged(handler) end def remove_PropertyChanged(handler) end end

    Read the article

  • creating objects in list

    - by prince23
    List myList = new List { new Users{ Name="Kumar", Gender="M", Age=75, Parent="All"}, new Users{ Name="Suresh",Gender="M", Age=50, Parent="Kumar"}, new Users{ Name="Bennette", Gender="F",Age=45, Parent="Kumar"}, new Users{ Name="kian", Gender="M",Age=20, Parent="Suresh"}, new Users{ Name="Nathani", Gender="M",Age=15, Parent="Suresh"}, new Users{ Name="Peter", Gender="M",Age=90, Parent="All"}, new Users{ Name="Mica", Age=56, Gender="M",Parent="Peter"}, new Users{ Name="Linderman", Gender="M",Age=51, Parent="Peter"}, new Users{ Name="john", Age=25, Gender="M",Parent="Mica"}, new Users{ Name="tom", Gender="M",Age=21, Parent="Mica"}, new Users{ Name="Ando", Age=64, Gender="M",Parent="All"}, new Users{ Name="Maya", Age=24, Gender="M",Parent="Ando"}, new Users{ Name="Niki Sanders", Gender="F",Age=2, Parent="Maya"}, new Users{ Name="Angela Patrelli", Gender="F",Age=3, Parent="Maya"}, }; now i need to format the data like here i need to check the parent based on the parent i will be creating objects under the parent objects now { Name="Kumar", Gender="M", Age=75, Parent="All" } this is the top level as a property Parent ="all" now under parent object kumar here we again create a new object to store these information under object(kumar who is the parent) new Users{ Name="Suresh",Gender="M", Age=50, Parent="Kumar"}, new Users{ Name="Bennette", Gender="F",Age=45, Parent="Kumar"}, what i need to do here is i need to check the parent based on the parent create further objects under it ex: i need to achive like this. looking for the syntax how i can do it. public class SampleProjectData { public static ObservableCollection<Product> GetSampleData() { DateTime dtS = DateTime.Now; ObservableCollection<Product> teams = new ObservableCollection<Product>(); teams.Add(new Product() { PDName = "Product1", OverallStartTime = dtS, OverallEndTime = dtS + TimeSpan.FromDays(3), }); Project emp = new Project() { PName = "Project1", OverallStartTime = dtS + TimeSpan.FromDays(1), OverallEndTime = dtS + TimeSpan.FromDays(6) }; emp.Tasks.Add(new Task() { StartTime = dtS, EndTime = dtS + TimeSpan.FromDays(2), TaskName = "John's Task 3" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(3), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "John's Task 2" }); teams[0].Projects.Add(emp); emp = new Project() { PName = "Project2", OverallStartTime = dtS + TimeSpan.FromDays(1.5), OverallEndTime = dtS + TimeSpan.FromDays(5.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Victor's Task" }); teams[0].Projects.Add(emp); emp = new Project() { PName = "Project3", OverallStartTime = dtS + TimeSpan.FromDays(2), OverallEndTime = dtS + TimeSpan.FromDays(5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Jason's Task 1" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(7), EndTime = dtS + TimeSpan.FromDays(9), TaskName = "Jason's Task 2" }); teams[0].Projects.Add(emp); teams.Add(new Product() { PDName = "Product2", OverallStartTime = dtS, OverallEndTime = dtS + TimeSpan.FromDays(3) }); emp = new Project() { PName = "Project4", OverallStartTime = dtS + TimeSpan.FromDays(0.5), OverallEndTime = dtS + TimeSpan.FromDays(3.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1.5), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Vicky's Task" }); teams[1].Projects.Add(emp); emp = new Project() { PName = "Project5", OverallStartTime = dtS + TimeSpan.FromDays(2), OverallEndTime = dtS + TimeSpan.FromDays(6) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(2.2), EndTime = dtS + TimeSpan.FromDays(3.8), TaskName = "Oleg's Task 1" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(5), EndTime = dtS + TimeSpan.FromDays(6), TaskName = "Oleg's Task 2" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(8), EndTime = dtS + TimeSpan.FromDays(9.6), TaskName = "Oleg's Task 3" }); teams[1].Projects.Add(emp); emp = new Project() { PName = "Project6", OverallStartTime = dtS + TimeSpan.FromDays(2.5), OverallEndTime = dtS + TimeSpan.FromDays(4.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(0.8), EndTime = dtS + TimeSpan.FromDays(2), TaskName = "Kim's Task" }); teams[1].Projects.Add(emp); teams.Add(new Product() { PDName = "Product3", OverallStartTime = dtS, OverallEndTime = dtS + TimeSpan.FromDays(3) }); emp = new Project() { PName = "Project7", OverallStartTime = dtS + TimeSpan.FromDays(5), OverallEndTime = dtS + TimeSpan.FromDays(7.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1.5), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Balaji's Task 1" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(5), EndTime = dtS + TimeSpan.FromDays(8), TaskName = "Balaji's Task 2" }); teams[2].Projects.Add(emp); emp = new Project() { PName = "Project8", OverallStartTime = dtS + TimeSpan.FromDays(3), OverallEndTime = dtS + TimeSpan.FromDays(6.3) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1.75), EndTime = dtS + TimeSpan.FromDays(2.25), TaskName = "Li's Task" }); teams[2].Projects.Add(emp); emp = new Project() { PName = "Project9", OverallStartTime = dtS + TimeSpan.FromDays(2), OverallEndTime = dtS + TimeSpan.FromDays(6) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(2), EndTime = dtS + TimeSpan.FromDays(3), TaskName = "Stacy's Task" }); teams[2].Projects.Add(emp); return teams; } } above is an sample data where i am grouping them with static data in the same way i need **to for teh data which is cmg from DB and i need to store them list** all these three data are comig from different services. and i am storing them in a list now i have three tables data Product , Project, Task. all the data are coming from webservies. i have created three list where i am storing the data in list. List<Project>objpro= new List<Project>(); List<Product>objproduct= new List<Product>(); LIst<Task>objTask= new List<Task>(); **now what i need to do is i need to do the mapping between these tables. if you see above. i have object of Product under Product i have added object of Project and then under project object i have added task object.** now from the above data which is stored in the list i need to do the same mapping between class. and group the data. public class Product : INotifyPropertyChanged { public Product() { this.Projects = new ObservableCollection<Project>(); } public string PDName { get; set; } public ObservableCollection<Project> Projects { get; set; } private DateTime _st; public DateTime OverallStartTime { get { return _st; } set { if (this._st != value) { TimeSpan dur = this._et - this._st; this._st = value; this.OnPropertyChanged("OverallStartTime"); this.OverallEndTime = value + dur; } } } private DateTime _et; public DateTime OverallEndTime { get { return _et; } set { if (this._et != value) { this._et = value; this.OnPropertyChanged("OverallEndTime"); } } } #region INotifyPropertyChanged Members protected void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } public class Project : INotifyPropertyChanged { public Project() { this.Tasks = new ObservableCollection<Task>(); } public string PName { get; set; } public ObservableCollection<Task> Tasks { get; set; } DateTime _st; public DateTime OverallStartTime { get { return _st; } set { if (this._st != value) { TimeSpan dur = this._et - this._st; this._st = value; this.OnPropertyChanged("OverallStartTime"); this.OverallEndTime = value + dur; } } } DateTime _et; public DateTime OverallEndTime { get { return _et; } set { if (this._et != value) { this._et = value; this.OnPropertyChanged("OverallEndTime"); } } } #region INotifyPropertyChanged Members protected void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } public class Task : INotifyPropertyChanged { public string TaskName { get; set; } DateTime _st; public DateTime StartTime { get { return _st; } set { if (this._st != value) { TimeSpan dur = this._et - this._st; this._st = value; this.OnPropertyChanged("StartTime"); this.EndTime = value + dur; } } } private DateTime _et; public DateTime EndTime { get { return _et; } set { if (this._et != value) { this._et = value; this.OnPropertyChanged("EndTime"); } } } #region INotifyPropertyChanged Members protected void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } hope my question is clear

    Read the article

  • Does The Clear Method On A Collection Release The Event Subscriptions?

    - by DaveB
    I have a collection private ObservableCollection<Contact> _contacts; In the constructor of my class I create it _contacts = new ObservableCollection<Contact>(); I have methods to add and remove items from my collection. I want to track changes to the entities in my collection which implement the IPropertyChanged interface so I subscribe to their PropertyChanged event. public void AddContact(Contact contact) { ((INotifyPropertyChanged)contact).PropertyChanged += new PropertyChangedEventHandler(Contact_PropertyChanged); _contacts.Add(contact); } public void AddContact(int index, Contact contact) { ((INotifyPropertyChanged)contact).PropertyChanged += new PropertyChangedEventHandler(Contact_PropertyChanged); _contacts.Insert(index, contact); } When I remove an entity from the collection, I unsubscribe from the PropertyChanged event. I am told this is to allow the entity to be garbage collected and not create memory issues. public void RemoveContact(Contact contact) { ((INotifyPropertyChanged)contact).PropertyChanged -= Contact_PropertyChanged; _contacts.Remove(contact); } So, I hope this is all good. Now, I need to clear the collection in one of my methods. My first thought would be to call _contacts.Clear(). Then I got to wondering if this releases those event subscriptions? Would I need to create my own clear method? Something like this: public void ClearContacts() { foreach(Contact contact in _contacts) { this.RemoveContact(contact); } } I am hoping one of the .NET C# experts here could clear this up for me or tell me what I am doing wrong.

    Read the article

  • Lists NotifyPropertyChanging

    - by Carlo
    Well BindingList and ObservableCollection work great to keep data updated and to notify when one of it's objects has changed. However, when notifying a property is about to change, I think these options are not very good. What I have to do right now to solve this (and I warn this is not elegant AT ALL), is to implement INotifyPropertyChanging on the list's type object and then tie that to the object that holds the list PropertyChanging event, or something like the following: // this object will be the type of the BindingList public class SomeObject : INotifyPropertyChanging, INotifyPropertyChanged { private int _intProperty = 0; private string _strProperty = String.Empty; public int IntProperty { get { return this._intProperty; } set { if (this._intProperty != value) { NotifyPropertyChanging("IntProperty"); this._intProperty = value; NotifyPropertyChanged("IntProperty"); } } } public string StrProperty { get { return this._strProperty; } set { if (this._strProperty != value) { NotifyPropertyChanging("StrProperty"); this._strProperty = value; NotifyPropertyChanged("StrProperty"); } } } #region INotifyPropertyChanging Members public event PropertyChangingEventHandler PropertyChanging; #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion public void NotifyPropertyChanging(string propertyName) { if (this.PropertyChanging != null) PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } public void NotifyPropertyChanged(string propertyName) { if (this.PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public class ObjectThatHoldsTheList : INotifyPropertyChanging, INotifyPropertyChanged { public BindingList<SomeObject> BindingList { get; set; } public ObjectThatHoldsTheList() { this.BindingList = new BindingList<SomeObject>(); } // this helps notifie Changing and Changed on Add private void AddItem(SomeObject someObject) { // this will tie the PropertyChanging and PropertyChanged events of SomeObject to this object // so it gets notifies because the BindingList does not notify PropertyCHANGING someObject.PropertyChanging += new PropertyChangingEventHandler(someObject_PropertyChanging); someObject.PropertyChanged += new PropertyChangedEventHandler(someObject_PropertyChanged); this.NotifyPropertyChanging("BindingList"); this.BindingList.Add(someObject); this.NotifyPropertyChanged("BindingList"); } // this helps notifies Changing and Changed on Delete private void DeleteItem(SomeObject someObject) { if (this.BindingList.IndexOf(someObject) > 0) { // this unlinks the handlers so the garbage collector can clear the objects someObject.PropertyChanging -= new PropertyChangingEventHandler(someObject_PropertyChanging); someObject.PropertyChanged -= new PropertyChangedEventHandler(someObject_PropertyChanged); } this.NotifyPropertyChanging("BindingList"); this.BindingList.Remove(someObject); this.NotifyPropertyChanged("BindingList"); } // this notifies an item in the list is about to change void someObject_PropertyChanging(object sender, PropertyChangingEventArgs e) { NotifyPropertyChanging("BindingList." + e.PropertyName); } // this notifies an item in the list has changed void someObject_PropertyChanged(object sender, PropertyChangedEventArgs e) { NotifyPropertyChanged("BindingList." + e.PropertyName); } #region INotifyPropertyChanging Members public event PropertyChangingEventHandler PropertyChanging; #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion public void NotifyPropertyChanging(string propertyName) { if (this.PropertyChanging != null) PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } public void NotifyPropertyChanged(string propertyName) { if (this.PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } Sorry, I know this is a lot of code, which takes me back to my main point IT'S A LOT OF CODE to implement this. So my question is, does anyone know a better, shorter, more elegant solution? Thanks for your time and suggestions.

    Read the article

  • Silverlight Cream for June 12, 2010 -- #880

    - by Dave Campbell
    In this Issue: Michael Washington, Diego Poza, Viktor Larsson, Brian Noyes, Charles Petzold, Laurent Bugnion, Anjaiah Keesari, David Anson, and Jeremy Likness. From SilverlightCream.com: My MEF Rant Read Michael Washington's discussion about MEF from someone that's got some experience, but not enough to remember the pain points... how it works, and what he'd like to see. Prism 4: What’s new and what’s next Diego Poza Why Office Hub is important for WP7 Viktor Larsson has another WP7 post up and he's talking about the Office Hub ... good description and maybe the first I've seen on the Office Hub. WCF RIA Services Part 1: Getting Started Brian Noyes has part 1 of a 10-part tutorial series on WCF RIA Services up at SilverlightShow. This first is the intro, but it's a good one. CompositionTarget.Rendering and RenderEventArgs Charles Petzold talks about CompositionTarget.Rendering and using it for calculating time span ... and it works in WPF and WP7 too... cool example from his WPF book, and all the code. Two small issues with Windows Phone 7 ApplicationBar buttons (and workaround) Laurent Bugnion has a post up from earlier this week that I missed describing problems with the WP7 ApplicationBar ... oh, and a workaround for it :) Animation in Silverlight Anjaiah Keesari has a really extensive post up on Silverlight animation, and this is an all-XAML thing... so buckle up we're going old-school :) Two fixes for my Silverlight SplitButton/MenuButton implementation - and true WPF support David Anson revisits and revises his SplitButton code based on a couple problem reports he received. Source for the button and the test project is included. Tips and Tricks for INotifyPropertyChanged Jeremy Likness is discussing INotifyPropertyChanged and describes an extension method. He does bring up a problem associated with this, so check that out. He finishes the post off with a discussion of "Observable Enumerables" Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Dependency Properties and Data Context in Silverlight 3

    - by Noam
    Hello, I am working with Silverlight 3 beta, and am having an issue. I have a page that has a user control that I worte on it. The user control has a dependency property on it. If the user control does not define a data context (hence using the parent's data context), all works well. But if the user control has its own data context, the dependency property's OnPropertyChanged method never gets called. Here is a sample: My Main Page: <UserControl x:Class="TestDepProp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:app="clr-namespace:TestDepProp" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400" Height="100"> <Grid x:Name="LayoutRoot" Background="White"> <Border BorderBrush="Blue" BorderThickness="3" CornerRadius="3"> <StackPanel Orientation="Horizontal"> <StackPanel Orientation="Vertical"> <TextBlock Text="Enter text here:" /> <TextBox x:Name="entryBlock" Text="{Binding Data, Mode=TwoWay}"/> <Button Content="Go!" Click="Button_Click" /> <TextBlock Text="{Binding Data}" /> </StackPanel> <Border BorderBrush="Blue" BorderThickness="3" CornerRadius="3" Margin="5"> <app:TestControl PropOnControl="{Binding Data}" /> </Border> </StackPanel> </Border> </Grid> </UserControl> Main Page code: using System.Windows; using System.Windows.Controls; namespace TestDepProp { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); MainPageData data = new MainPageData(); this.DataContext = data; } private void Button_Click(object sender, RoutedEventArgs e) { int i = 1; i++; } } } Main Page's data context: using System.ComponentModel; namespace TestDepProp { public class MainPageData:INotifyPropertyChanged { string _data; public string Data { get { return _data; } set { _data = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Data")); } } public MainPageData() { Data = "Initial Value"; } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion } } Control XAML: <UserControl x:Class="TestDepProp.TestControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:TestDepProp" > <Grid x:Name="LayoutRoot" Background="White"> <StackPanel Orientation="Vertical" Margin="10" > <TextBlock Text="This should change:" /> <TextBlock x:Name="ControlValue" Text="Not Set" /> </StackPanel> </Grid> </UserControl> Contol code: using System.Windows; using System.Windows.Controls; namespace TestDepProp { public partial class TestControl : UserControl { public TestControl() { InitializeComponent(); // Comment out next line for DP to work DataContext = new MyDataContext(); } #region PropOnControl Dependency Property public string PropOnControl { get { return (string)GetValue(PropOnControlProperty); } set { SetValue(PropOnControlProperty, value); } } public static readonly DependencyProperty PropOnControlProperty = DependencyProperty.Register("PropOnControl", typeof(string), typeof(TestControl), new PropertyMetadata(OnPropOnControlPropertyChanged)); private static void OnPropOnControlPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { TestControl _TestControl = d as TestControl; if (_TestControl != null) { _TestControl.ControlValue.Text = e.NewValue.ToString(); } } #endregion PropOnControl Dependency Property } } Control's data context: using System.ComponentModel; namespace TestDepProp { public class MyDataContext : INotifyPropertyChanged { #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion } } To try it out, type something in the text box, and hit the Go button. Comment out the data context in the controls code to see that it starts to work. Hope someone has an idea as to what is going on.

    Read the article

  • Bug with Set / Get Accessor in .Net 3.5

    - by MarkPearl
    I spent a few hours scratching my head on this one... So I thought I would blog about it in case someone else had the same headache. Assume you have a class, and you are wanting to use the INotifyPropertyChanged interface so that when you bind to an instance of the class, you get the magic sauce of binding to do you updates to the UI. Well, I had a special instance where I wanted one of the properties of the class to add some additional formatting to itself whenever someone changed its value (see the code below).   class Test: INotifyPropertyChanged {     private string_inputValue;     public stringInputValue     {         get        {             return_inputValue;         }         set        {             if(value!= _inputValue)             {                 _inputValue = value+ "Extra Stuff";                 NotifyPropertyChanged("InputValue");                     }         }     }     public eventPropertyChangedEventHandler PropertyChanged;     public voidNotifyPropertyChanged(stringinfo)     {         if(PropertyChanged != null)         {             PropertyChanged(this, newPropertyChangedEventArgs(info));         }     } }   Everything looked fine, but when I ran it in my WPF project, the textbox I was binding to would not update? I couldn’t understand it! I thought the code made sense, so why wasn’t it working? Eventually StackOverflow came to the rescue, where I was told that it was a bug in the .Net 3.5 Runtime and that a fix was scheduled in .Net 4 For those who have the same problem, here is the workaround… You need to put the NotifyPropertyChanged method on the application thread! public string InputValue { get { return _inputValue; } set { if (value != _inputValue) { _inputValue = value + "Extra Stuff"; // // React to the type of measurement // Application.Current.Dispatcher.BeginInvoke((Action)delegate { NotifyPropertyChanged("InputValue"); }); } } }

    Read the article

  • Binding not writing to datasource on .NET Compact Framework Form -- works on Full Framework

    - by Dave Welling
    I have a problem with a bound user control writing back to it's datasource on a NetCF forms application. The application is too complex to post code, so I made a toy version to show you. I create a form, usercontrol with a combobox, a class (testBind) and another class (TestLookup). I bind a property of the usercontrol ("value") to a property ("selectedValue") on the testBind class. The testBind class implements INotifyPropertyChanged. I create a few fascade methods on the user control to bind the contained combobox to a BindingList(of TestLookup). I create a button to show the value of the testBind bound property (in a MessageBox). The messagebox returns "-1" every time regardless of the combobox entry selected. I can take the EXACT same code, paste it in a full framework Forms app and it will return the correct value of the selected combobox entry. Imports System.ComponentModel Public Class Form2 Inherits Form Private _testBind1 As testBind Private _testUserControlX As UserControlX Friend WithEvents _buttonX As System.Windows.Forms.Button Public Sub New() _buttonX = New System.Windows.Forms.Button _buttonX.Location = New System.Drawing.Point(126, 228) _buttonX.Size = New System.Drawing.Size(70, 21) _testBind1 = New testBind _testUserControlX = New UserControlX() Dim _lookup As New System.ComponentModel.BindingList(Of TestLookup)() _lookup.Add(New TestLookup(1, "text1")) _lookup.Add(New TestLookup(2, "text2")) _testUserControlX.DataSource = _lookup _testUserControlX.DisplayMember = "Text" _testUserControlX.ValueMember = "ID" _testUserControlX.DataBindings.Add("Value", _testBind1, "SelectedID", False, DataSourceUpdateMode.OnValidation) MinimizeBox = False Controls.Add(_testUserControlX) Controls.Add(_buttonX) End Sub Private Sub ButtonX_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _buttonX.Click MessageBox.Show(_testBind1.SelectedID.ToString()) End Sub Public Class testBind Implements System.ComponentModel.INotifyPropertyChanged Private _selectedRow As Integer = -1 Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged Protected Sub OnPropertyChanged(ByVal PropertyName As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(PropertyName)) End Sub Public Property SelectedID() As Integer Get Return _selectedRow End Get Set(ByVal value As Integer) _selectedRow = value OnPropertyChanged("SelectedID") End Set End Property End Class Public Class TestLookup Private _text As String Private _id As Integer Public Sub New(ByVal id As Integer, ByVal text As String) _text = text _id = id End Sub Public Property ID() As Integer Get Return _id End Get Set(ByVal value As Integer) _id = value End Set End Property Public Property Text() As String Get Return _text End Get Set(ByVal value As String) _text = value End Set End Property End Class End Class Public Class UserControlX Inherits System.Windows.Forms.UserControl Friend WithEvents ComboBox1 As System.Windows.Forms.ComboBox Public Sub New() Me.ComboBox1 = New System.Windows.Forms.ComboBox Me.Controls.Add(Me.ComboBox1) End Sub Public Property Value() As Integer Get Return ComboBox1.SelectedValue End Get Set(ByVal value As Integer) ComboBox1.SelectedValue = value End Set End Property Public Property DataSource() As Object Get Return ComboBox1.DataSource End Get Set(ByVal value As Object) ComboBox1.DataSource = value End Set End Property Public Property ValueMember() As String Get Return ComboBox1.ValueMember End Get Set(ByVal value As String) ComboBox1.ValueMember = value End Set End Property Public Property DisplayMember() As String Get Return ComboBox1.DisplayMember End Get Set(ByVal value As String) ComboBox1.DisplayMember = value End Set End Property End Class

    Read the article

  • WPF-Prism CanExecute method not being called

    - by nareshbhatia
    I am coding a simple login UserControl with two TextBoxes (Username and Password) and a Login button. I want the Login button to be enabled only when the username and password fields are filled in. I am using Prism and MVVM. The LoginViewModel contains a property called LoginCommand that is bound to the Login button. I have a CanLoginExecute() method in my ViewModel but it fires only when the application comes up and then never again. So the Login button is never enabled. What am I missing? Here's my xaml: <TextBox x:Name="username" Text="{Binding Path=Username, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" /> <TextBox x:Name="password" Text="{Binding Path=Password, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" /> <Button Content="Login" cmnd:Click.Command="{Binding LoginCommand}" /> Here's my ViewModel class LoginViewModel : IDataErrorInfo, INotifyPropertyChanged { public LoginViewModel() { this.LoginCommand = new DelegateCommand<object>( this.LoginExecute, this.CanLoginExecute); } private Boolean CanLoginExecute(object dummyObject) { return (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)) ? false : true; } private void LoginExecute(object dummyObject) { if (CheckCredentials(Username, Password)) { .... } } #region IDataErrorInfo Members public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { string result = null; if (columnName == "Username") { if (string.IsNullOrEmpty(Username)) result = "Please enter a username"; } else if (columnName == "Password") { if (string.IsNullOrEmpty(Password)) result = "Please enter a password"; } return result; } } #endregion // IDataErrorInfo Members #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion // INotifyPropertyChanged Members #region Properties private String _username; public String Username { get { return _username; } set { if (value == _username) return; _username = value; this.OnPropertyChanged("Username"); } } private String _password; public String Password { get { return _password; } set { if (value == _password) return; _password = value; this.OnPropertyChanged("Password"); } } public ICommand LoginCommand { get; private set; } #endregion // Properties }

    Read the article

  • WPF - Binding problem

    - by Erez
    Why after clicking the button the text in the textblock doesn't change ? XAML: <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <TextBlock Text="{Binding Name}"/> <Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button> </Grid> Code behind: public partial class Window1 : Window, INotifyPropertyChanged { private Person _myPerson; public Person MyPerson { get { return _myPerson; } set { _myPerson = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("MyPerson")); } } } public Window1() { MyPerson = new Person { Name = "A" }; DataContext = MyPerson; InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { MyPerson = new Person { Name = "B" }; } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion }

    Read the article

  • Big smart ViewModels, dumb Views, and any model, the best MVVM approach?

    - by Edward Tanguay
    The following code is a refactoring of my previous MVVM approach (Fat Models, skinny ViewModels and dumb Views, the best MVVM approach?) in which I moved the logic and INotifyPropertyChanged implementation from the model back up into the ViewModel. This makes more sense, since as was pointed out, you often you have to use models that you either can't change or don't want to change and so your MVVM approach should be able to work with any model class as it happens to exist. This example still allows you to view the live data from your model in design mode in Visual Studio and Expression Blend which I think is significant since you could have a mock data store that the designer connects to which has e.g. the smallest and largest strings that the UI can possibly encounter so that he can adjust the design based on those extremes. Questions: I'm a bit surprised that I even have to "put a timer" in my ViewModel since it seems like that is a function of INotifyPropertyChanged, it seems redundant, but it was the only way I could get the XAML UI to constantly (once per second) reflect the state of my model. So it would be interesting to hear anyone who may have taken this approach if you encountered any disadvantages down the road, e.g. with threading or performance. The following code will work if you just copy the XAML and code behind into a new WPF project. XAML: <Window x:Class="TestMvvm73892.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestMvvm73892" Title="Window1" Height="300" Width="300"> <Window.Resources> <ObjectDataProvider x:Key="DataSourceCustomer" ObjectType="{x:Type local:CustomerViewModel}" MethodName="GetCustomerViewModel"/> </Window.Resources> <DockPanel DataContext="{StaticResource DataSourceCustomer}"> <StackPanel DockPanel.Dock="Top" Orientation="Horizontal"> <TextBlock Text="{Binding Path=FirstName}"/> <TextBlock Text=" "/> <TextBlock Text="{Binding Path=LastName}"/> </StackPanel> <StackPanel DockPanel.Dock="Top" Orientation="Horizontal"> <TextBlock Text="{Binding Path=TimeOfMostRecentActivity}"/> </StackPanel> </DockPanel> </Window> Code Behind: using System; using System.Windows; using System.ComponentModel; using System.Threading; namespace TestMvvm73892 { public partial class Window1 : Window { public Window1() { InitializeComponent(); } } //view model public class CustomerViewModel : INotifyPropertyChanged { private string _firstName; private string _lastName; private DateTime _timeOfMostRecentActivity; private Timer _timer; public string FirstName { get { return _firstName; } set { _firstName = value; this.RaisePropertyChanged("FirstName"); } } public string LastName { get { return _lastName; } set { _lastName = value; this.RaisePropertyChanged("LastName"); } } public DateTime TimeOfMostRecentActivity { get { return _timeOfMostRecentActivity; } set { _timeOfMostRecentActivity = value; this.RaisePropertyChanged("TimeOfMostRecentActivity"); } } public CustomerViewModel() { _timer = new Timer(CheckForChangesInModel, null, 0, 1000); } private void CheckForChangesInModel(object state) { Customer currentCustomer = CustomerViewModel.GetCurrentCustomer(); MapFieldsFromModeltoViewModel(currentCustomer, this); } public static CustomerViewModel GetCustomerViewModel() { CustomerViewModel customerViewModel = new CustomerViewModel(); Customer currentCustomer = CustomerViewModel.GetCurrentCustomer(); MapFieldsFromModeltoViewModel(currentCustomer, customerViewModel); return customerViewModel; } public static void MapFieldsFromModeltoViewModel(Customer model, CustomerViewModel viewModel) { viewModel.FirstName = model.FirstName; viewModel.LastName = model.LastName; viewModel.TimeOfMostRecentActivity = model.TimeOfMostRecentActivity; } public static Customer GetCurrentCustomer() { return Customer.GetCurrentCustomer(); } //INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } } //model public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public DateTime TimeOfMostRecentActivity { get; set; } public static Customer GetCurrentCustomer() { return new Customer { FirstName = "Jim", LastName = "Smith", TimeOfMostRecentActivity = DateTime.Now }; } } }

    Read the article

  • DependencyProperty ignores OnPropertyChanged();

    - by Kovpaev Alexey
    I have PointsListView and PointContainer: INotifyPropertyChanged, ICollection<Point>. public class PointContainer: INotifyPropertyChanged, ICollection<Point> { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) PropertyChanged(this, e); } public IEnumerable<Point> Points { get { return points.Values; } } public void Clear() { points.Clear(); OnPropertyChanged(new PropertyChangedEventArgs("Points")); } ... } For the reliability I made a binding from code: private void BindPointContainerToListView() { Binding binding = new Binding(); binding.Source = PointContainer; binding.Path = new PropertyPath("Points"); PointsListView.SetBinding(ListView.ItemsSourceProperty, binding); } Why when change PointContainer is not automatically updated PointsListView.ItemsSource. PointsListView.Items.Refresh (); solves the problem, but why does not work automatically? What am I doing wrong?

    Read the article

  • What causes a WPF ListCollectionView that uses custom sorting to re-sort its items?

    - by Drew Noakes
    Consider this code (type names genericised for the purposes of example): // Bound to ListBox.ItemsSource _items = new ObservableCollection<Item>(); // ...Items are added here ... // Specify custom IComparer for this collection view _itemsView = CollectionViewSource.GetDefaultView(_items) ((ListCollectionView)_itemsView).CustomSort = new ItemComparer(); When I set CustomSort, the collection is sorted as I expect. However I require the data to re-sort itself at runtime in response to the changing of the properties on Item. The Item class derives from INotifyPropertyChanged and I know that the property fires correctly as my data template updates the values on screen, only the sorting logic is not being called. I have also tried raising INotifyPropertyChanged.PropertyChanged passing an empty string, to see if a generic notification would cause the sorting to be initiated. No bananas. EDIT In response to Kent's suggestion I thought I'd point out that sorting the items using this has the same result, namely that the collection sorts once but does not re-sort as the data changes: _itemsView.SortDescriptions.Add( new SortDescription("PropertyName", ListSortDirection.Ascending));

    Read the article

  • WPF Datatemplate + ItemsControl each item uses > 1 MB Memory?

    - by Matt H.
    Does that sound right to anyone???? I have an ItemsControl that displays data from a custom object that implements iNotifyPropertyChanged. The DataTemplate consists of: Border 3 buttons 5 textboxes An ellipse A Bindable RichTextBox (custom class that inherits from RichTextBox... so I could make Document a dependency property (to support binding)) Several grids and stackpanels for layout It uses: Styles (stored in a resource dictionary higher up the tree) Styles affect: colors, thicknesses, and text properties: which are data-bound to a "settings" class that implements iNotifyPropertyChanged, so the user can change display settings That's it! So what gives? I've also noticed that when I empty and remove the ItemsControl, memory isn't freed. over 5000 instances of "CommandBindingCollection" and "WeakReference" are CREATED (using ANTS profiler). And huge number of EffectiveValueEntry objects are created too. So really, what gives!!! :-) Thanks for your insight! Management needs this project soon but in its current state, it's unreleasable.

    Read the article

  • Validation in Silverlight

    - by Timmy Kokke
    Getting started with the basics Validation in Silverlight can get very complex pretty easy. The DataGrid control is the only control that does data validation automatically, but often you want to validate your own entry form. Values a user may enter in this form can be restricted by the customer and have to fit an exact fit to a list of requirements or you just want to prevent problems when saving the data to the database. Showing a message to the user when a value is entered is pretty straight forward as I’ll show you in the following example.     This (default) Silverlight textbox is data-bound to a simple data class. It has to be bound in “Two-way” mode to be sure the source value is updated when the target value changes. The INotifyPropertyChanged interface must be implemented by the data class to get the notification system to work. When the property changes a simple check is performed and when it doesn’t match some criteria an ValidationException is thrown. The ValidatesOnExceptions binding attribute is set to True to tell the textbox it should handle the thrown ValidationException. Let’s have a look at some code now. The xaml should contain something like below. The most important part is inside the binding. In this case the Text property is bound to the “Name” property in TwoWay mode. It is also told to validate on exceptions. This property is false by default.   <StackPanel Orientation="Horizontal"> <TextBox Width="150" x:Name="Name" Text="{Binding Path=Name, Mode=TwoWay, ValidatesOnExceptions=True}"/> <TextBlock Text="Name"/> </StackPanel>   The data class in this first example is a very simplified person class with only one property: string Name. The INotifyPropertyChanged interface is implemented and the PropertyChanged event is fired when the Name property changes. When the property changes a check is performed to see if the new string is null or empty. If this is the case a ValidationException is thrown explaining that the entered value is invalid.   public class PersonData:INotifyPropertyChanged { private string _name; public string Name { get { return _name; } set { if (_name != value) { if(string.IsNullOrEmpty(value)) throw new ValidationException("Name is required"); _name = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } } public event PropertyChangedEventHandler PropertyChanged=delegate { }; } The last thing that has to be done is letting binding an instance of the PersonData class to the DataContext of the control. This is done in the code behind file. public partial class Demo1 : UserControl { public Demo1() { InitializeComponent(); this.DataContext = new PersonData() {Name = "Johnny Walker"}; } }   Error Summary In many cases you would have more than one entry control. A summary of errors would be nice in such case. With a few changes to the xaml an error summary, like below, can be added.           First, add a namespace to the xaml so the control can be used. Add the following line to the header of the .xaml file. xmlns:Controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"   Next, add the control to the layout. To get the result as in the image showed earlier, add the control right above the StackPanel from the first example. It’s got a small margin to separate it from the textbox a little.   <Controls:ValidationSummary Margin="8"/>   The ValidationSummary control has to be notified that an ValidationException occurred. This can be done with a small change to the xaml too. Add the NotifyOnValidationError to the binding expression. By default this value is set to false, so nothing would be notified. Set the property to true to get it to work.   <TextBox Width="150" x:Name="Name" Text="{Binding Name, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}"/>   Data annotation Validating data in the setter is one option, but not my personal favorite. It’s the easiest way if you have a single required value you want to check, but often you want to validate more. Besides, I don’t consider it best practice to write logic in setters. The way used by frameworks like WCF Ria Services is the use of attributes on the properties. Instead of throwing exceptions you have to call the static method ValidateProperty on the Validator class. This call stays always the same for a particular property, not even when you change the attributes on the property. To mark a property “Required” you can use the RequiredAttribute. This is what the Name property is going to look like:   [Required] public string Name { get { return _name; } set { if (_name != value) { Validator.ValidateProperty(value, new ValidationContext(this, null, null){ MemberName = "Name" }); _name = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } }   The ValidateProperty method takes the new value for the property and an instance of ValidationContext. The properties passed to the constructor of the ValidationContextclass are very straight forward. This part is the same every time. The only thing that changes is the MemberName property of the ValidationContext. Property has to hold the name of the property you want to validate. It’s the same value you provide the PropertyChangedEventArgs with. The System.ComponentModel.DataAnnotation contains eight different validation attributes including a base class to create your own. They are: RequiredAttribute Specifies that a value must be provided. RangeAttribute The provide value must fall in the specified range. RegularExpressionAttribute Validates is the value matches the regular expression. StringLengthAttribute Checks if the number of characters in a string falls between a minimum and maximum amount. CustomValidationAttribute Use a custom method to validate the value. DataTypeAttribute Specify a data type using an enum or a custom data type. EnumDataTypeAttribute Makes sure the value is found in a enum. ValidationAttribute A base class for custom validation attributes All of these will ensure that an validation exception is thrown, except the DataTypeAttribute. This attribute is used to provide some additional information about the property. You can use this information in your own code.   [Required] [Range(0,125,ErrorMessage = "Value is not a valid age")] public int Age {   It’s no problem to stack different validation attributes together. For example, when an Age is required and must fall in the range from 0 to 125:   [Required, StringLength(255,MinimumLength = 3)] public string Name {   Or in one row like this, for a required Name with at least 3 characters and a maximum of 255:   Delayed validation Having properties marked as required can be very useful. The only downside to the technique described earlier is that you have to change the value in order to get it validated. What if you start out with empty an empty entry form? All fields are empty and thus won’t be validated. With this small trick you can validate at the moment the user click the submit button.   <TextBox Width="150" x:Name="NameField" Text="{Binding Name, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True, UpdateSourceTrigger=Explicit}"/>   By default, when a TwoWay bound control looses focus the value is updated. When you added validation like I’ve shown you earlier, the value is validated. To overcome this, you have to tell the binding update explicitly by setting the UpdateSourceTrigger binding property to Explicit:   private void SubmitButtonClick(object sender, RoutedEventArgs e) { NameField.GetBindingExpression(TextBox.TextProperty).UpdateSource(); }   This way, the binding is in two direction but the source is only updated, thus validated, when you tell it to. In the code behind you have to call the UpdateSource method on the binding expression, which you can get from the TextBox.   Conclusion Data validation is something you’ll probably want on almost every entry form. I always thought it was hard to do, but it wasn’t. If you can throw an exception you can do validation. If you want to know anything more in depth about something I talked about in this article let me know. I might write an entire post to that.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >