Search Results

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

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

  • Fixing the #mvvmlight code snippets in Visual Studio 11

    - by Laurent Bugnion
    If you installed the latest MVVM Light version for Windows 8, you may encounter an issue where code snippets are not displayed correctly in the Intellisense popup. I am working on a fix, but for now here is how you can solve the issue manually. The code snippets MVVM Light, when installed correctly, will install a set of code snippets that are very useful to allow you to type less code. As I use to say, code is where bugs are, so you want to type as little of that as possible ;) With code snippets, you can easily auto-insert segments of code and easily replace the keywords where needed. For instance, every coder who uses MVVM as his favorite UI pattern for XAML based development is used to the INotifyPropertyChanged implementation, and how boring it can be to type these “observable properties”. Obviously a good fix would be something like an “Observable” attribute, but that is not supported in the language or the framework for the moment. Another fix involves “IL weaving”, which is a post-build operation modifying the generate IL code and inserting the “RaisePropertyChanged” instruction. I admire the invention of those who developed that, but it feels a bit too much like magic to me. I prefer more “down to earth” solutions, and thus I use the code snippets. Fixing the issue Normally, you should see the code snippets in Intellisense when you position your cursor in a C# file and type mvvm. All MVVM Light snippets start with these 4 letters. Normal MVVM Light code snippets However, in Windows 8 CP, there is an issue that prevents them to appear correctly, so you won’t see them in the Intellisense windows. To restore that, follow the steps: In Visual Studio 11, open the menu Tools, Code Snippets Manager. In the combobox, select Visual C#. Press Add… Navigate to C:\Program Files (x86)\Laurent Bugnion (GalaSoft)\Mvvm Light Toolkit\SnippetsWin8 and select the CSharp folder. Press Select Folder. Press OK to close the Code Snippets Manager. Now if you type mvvm in a C# file, you should see the snippets in your Intellisense window. Cheers Laurent   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • Silverlight Cream for June 15, 2010 - 2 -- #883

    - by Dave Campbell
    In this Issue: Vibor Cipan, Chris Klug, Pete Brown, Kirupa, and Xianzhong Zhu. Shoutouts (thought I gave up on them, didn't you?): Jesse Liberty has the companion video to his WP7 OData post up: New Video: Master/Detail in WinPhone 7 with oData Michael Scherotter who made the first Ball Watch SL1 app back in the day, has a Virtual Event: Creating an Entry for the BALL Watch Silverlight Contest... sounds like the thing to do if you want in on this :) Even if you don't speak Portuguese, you can check this out: MSN Brazil Uses Silverlight to Showcase the 2010 FIFA World Cup South Africa Erik Mork and crew have their latest up: This Week in Silverlight – Teched and Quizes Michael Klucher has a post up to give you some relief if you're having Trouble Installing the Windows Phone Developer Tools Portuguese above and now French... Jeremy Alles has a post up about [WP7] Windows Phone 7 challenge for french readers ! Just a note, not that it makes any difference, but Adam Kinney turned @SilverlightNews over to me today. I am the only one that has ever posted on it, but still having it all to myself feels special :) From SilverlightCream.com: Silverlight 4 tutorial: HOW TO use PathListBox and Sample Data Crank up that new version of Blend and follow along with Vibor Cipan's PathListBox tutorial ... oh, and sample data too. Cool INotifyPropertyChanged implementation Chris Klug shows off some INotifyPropertyChange goodness he is not implementing, and credits a blog by Manuel Felicio for some inspiration. Check out that post as well... I've tagged his blog... I needed *another* one :) Silverlight Tip: Using LINQ to Select the Largest Available Webcam Resolution With no Silverlight Tip of the Day today, Pete Brown stepped up with this tip for finding the largest available webcam resolution using LINQ ... and read the comment from Rene as well. Creating a Master-Detail UI in Blend Kirupa has a very nice Master/Detail UI post up with backrounder info and the code for the project. There's a running example in the post for you to get an idea what you're learning. Get started with Farseer Physics 2.1.3 in Silverlight 3 Xianzhong Zhu has a Silverlight 3 tutorial up for Farseer Physics 2.1.3 ... might track for Silverlight 4, but hey, WP7 is kinda/sort Silverlight 3, right? ... lots of code and external links. 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

  • Defining a service layer: the text-based adventure

    - by Stacy Vicknair
    Applications these days have more options than ever for a user interface, and it’s only going to grow. A successful product might require native applications for mobile devices, a regular web implementation, or even a gaming console. These systems often will be centralized and data driven. The solution is one that’s fairly solitary, a service layer! Simply put, take what’s shared and put it behind a physical or abstract layer that defines the boundary between the specific user interface and the shared content.   I know, I know, none of this is complicated. But some times it can be difficult to discern what belongs on which side of the line. For instance, say we’re creating a service that will provide content for both an ASP.NET MVC application and a WP7 application. Although the content served to each application is the same, there are different paradigms and patterns for displaying that data in the different environments. In ASP.NET MVC, you may create a model specific to a page that combines necessary information. In the WP7 application you might require different sets of data that you will connect via MVVM with the view. The general rule of thumb is that any shared content, business rules, or data should exist separately. Any element that is specific to the current UI implementation should be included in a separate library or with the UI implementation itself. The WP7 application doesn’t need my MVC specific model classes. My MVC application doesn’t require those INotifyPropertyChanged viewmodels that the WP7 application depends on. In both cases, there should be additional processing done above the service layer to massage the data to the application’s specific needs.   Service-ocalypse: the text based adventure What helps me the most about deciding whether or not something belongs coupled to the UI implementation or in the shared implementation is thinking of the simplest implementation you could have: a console application. You might have played a game like Peasant’s Quest: The console app is the text based adventure game version of your application. If you’re service was consumed in its simplest form, you would simply have a console based API for it that issues requests. Maybe those requests aren’t SWIM TO BOAT, but they might be CREATE USER JOHN. If I issue a request, I expect that request to be issued to the service. If the service has any exceptions or issues with my input, that business logic should be encapsulated in that service, not implemented in the UI. The service layer should be your functional application in its entirety, and anything above that layer should only assist with the display of that information.

    Read the article

  • How to configure a Custom Datacontract Serializer or XMLSerializer

    - by user364445
    Im haveing some xml that have this structure <Person Id="*****" Name="*****"> <AccessControlEntries> <AccessControlEntry Id="*****" Name="****"/> </AccessControlEntries> <AccessControls /> <IdentityGroups> <IdentityGroup Id="****" Name="*****" /> </IdentityGroups></Person> and i also have this entities [DataContract(IsReference = true)] public abstract class EntityBase { protected bool serializing; [DataMember(Order = 1)] [XmlAttribute()] public string Id { get; set; } [DataMember(Order = 2)] [XmlAttribute()] public string Name { get; set; } [OnDeserializing()] public void OnDeserializing(StreamingContext context) { this.Initialize(); } [OnSerializing()] public void OnSerializing(StreamingContext context) { this.serializing = true; } [OnSerialized()] public void OnSerialized(StreamingContext context) { this.serializing = false; } public abstract void Initialize(); public string ToXml() { var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; var sb = new System.Text.StringBuilder(); using (var writer = System.Xml.XmlWriter.Create(sb, settings)) { var serializer = new XmlSerializer(this.GetType()); serializer.Serialize(writer, this); } return sb.ToString(); } } [DataContract()] public abstract class Identity : EntityBase { private EntitySet<AccessControlEntry> accessControlEntries; private EntitySet<IdentityGroup> identityGroups; public Identity() { Initialize(); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "AccessControlEntries")] public EntitySet<AccessControlEntry> AccessControlEntries { get { if ((this.serializing && (this.accessControlEntries==null || this.accessControlEntries.HasLoadedOrAssignedValues == false))) { return null; } return accessControlEntries; } set { accessControlEntries.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] [Association(Name = "IdentityGroups")] public EntitySet<IdentityGroup> IdentityGroups { get { if ((this.serializing && (this.identityGroups == null || this.identityGroups.HasLoadedOrAssignedValues == false))) { return null; } return identityGroups; } set { identityGroups.Assign(value); } } private void attach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Add(this); } private void dettach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Remove(this); } private void attach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } private void dettach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } public override void Initialize() { this.accessControlEntries = new EntitySet<AccessControlEntry>( new Action<AccessControlEntry>(this.attach_accessControlEntry), new Action<AccessControlEntry>(this.dettach_accessControlEntry)); this.identityGroups = new EntitySet<IdentityGroup>( new Action<IdentityGroup>(this.attach_IdentityGroup), new Action<IdentityGroup>(this.dettach_IdentityGroup)); } } [XmlType(TypeName = "AccessControlEntry")] public class AccessControlEntry : EntityBase, INotifyPropertyChanged { private EntitySet<Service> services; private EntitySet<Identity> identities; private EntitySet<Permission> permissions; public AccessControlEntry() { services = new EntitySet<Service>(new Action<Service>(attach_Service), new Action<Service>(dettach_Service)); identities = new EntitySet<Identity>(new Action<Identity>(attach_Identity), new Action<Identity>(dettach_Identity)); permissions = new EntitySet<Permission>(new Action<Permission>(attach_Permission), new Action<Permission>(dettach_Permission)); } [DataMember(Order = 3, EmitDefaultValue = false)] public EntitySet<Permission> Permissions { get { if ((this.serializing && (this.permissions.HasLoadedOrAssignedValues == false))) { return null; } return permissions; } set { permissions.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] public EntitySet<Identity> Identities { get { if ((this.serializing && (this.identities.HasLoadedOrAssignedValues == false))) { return null; } return identities; } set { identities.Assign(identities); } } [DataMember(Order = 5, EmitDefaultValue = false)] public EntitySet<Service> Services { get { if ((this.serializing && (this.services.HasLoadedOrAssignedValues == false))) { return null; } return services; } set { services.Assign(value); } } private void attach_Permission(Permission entity) { entity.AccessControlEntires.Add(this); } private void dettach_Permission(Permission entity) { entity.AccessControlEntires.Remove(this); } private void attach_Identity(Identity entity) { entity.AccessControlEntries.Add(this); } private void dettach_Identity(Identity entity) { entity.AccessControlEntries.Remove(this); } private void attach_Service(Service entity) { entity.AccessControlEntries.Add(this); } private void dettach_Service(Service entity) { entity.AccessControlEntries.Remove(this); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(name)); } #endregion public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "Person")] public class Person : Identity { private EntityRef<Login> login; [DataMember(Order = 3)] [XmlAttribute()] public string Nombre { get; set; } [DataMember(Order = 4)] [XmlAttribute()] public string Apellidos { get; set; } [DataMember(Order = 5)] public Login Login { get { return login.Entity; } set { var previousValue = this.login.Entity; if (((previousValue != value) || (this.login.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.login.Entity = null; previousValue.Person = null; } this.login.Entity = value; if ((value != null)) value.Person = this; } } } public override void Initialize() { base.Initialize(); } } [DataContract()] [XmlType(TypeName = "Login")] public class Login : EntityBase { private EntityRef<Person> person; [DataMember(Order = 3)] public string UserID { get; set; } [DataMember(Order = 4)] public string Contrasena { get; set; } [DataMember(Order = 5)] public Domain Dominio { get; set; } public Person Person { get { return person.Entity; } set { var previousValue = this.person.Entity; if (((previousValue != value) || (this.person.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.person.Entity = null; previousValue.Login = null; } this.person.Entity = value; if ((value != null)) value.Login = this; } } } public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "IdentityGroup")] public class IdentityGroup : Identity { private EntitySet<Identity> memberIdentities; public IdentityGroup() { Initialize(); } public override void Initialize() { this.memberIdentities = new EntitySet<Identity>(new Action<Identity>(this.attach_Identity), new Action<Identity>(this.dettach_Identity)); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "MemberIdentities")] public EntitySet<Identity> MemberIdentites { get { if ((this.serializing && (this.memberIdentities.HasLoadedOrAssignedValues == false))) { return null; } return memberIdentities; } set { memberIdentities.Assign(value); } } private void attach_Identity(Identity entity) { entity.IdentityGroups.Add(this); } private void dettach_Identity(Identity entity) { entity.IdentityGroups.Remove(this); } } [DataContract()] [XmlType(TypeName = "Group")] public class Group : Identity { public override void Initialize() { throw new NotImplementedException(); } } but the ToXml() response something like this <Person xmlns:xsi="************" xmlns:xsd="******" ID="******" Name="*****"/><AccessControlEntries/></Person> but what i want is something like this <Person Id="****" Name="***" Nombre="****"> <AccessControlEntries/> <IdentityGroups/> </Person>

    Read the article

  • Windows Presentation Foundation 4.5 Cookbook Review

    - by Ricardo Peres
    As promised, here’s my review of Windows Presentation Foundation 4.5 Cookbook, that Packt Publishing kindly made available to me. It is an introductory book, targeted at WPF newcomers or users with few experience, following the typical recipes or cookbook style. Like all Packt Publishing books on development, each recipe comes with sample code that is self-sufficient for understanding the concepts it tries to illustrate. It starts on chapter 1 by introducing the most important concepts, the XAML language itself, what can be declared in XAML and how to do it, what are dependency and attached properties as well as markup extensions and events, which should give readers a most required introduction to how WPF works and how to do basic stuff. It moves on to resources on chapter 2, which also makes since, since it’s such an important concept in WPF. Next, chapter 3, come the panels used for laying controls on the screen, all of the out of the box panels are described with typical use cases. Controls come next in chapter 4; the difference between elements and controls is introduced, as well as content controls, headered controls and items controls, and all standard controls are introduced. The book shows how to change the way they look by using templates. The next chapter, 5, talks about top level windows and the WPF application object: how to access startup arguments, how to set the main window, using standard dialogs and there’s even a sample on how to have a irregularly-shaped window. This is one of the most important concepts in WPF: data binding, which is the theme for the following chapter, 6. All common scenarios are introduced, the binding modes, directions, triggers, etc. It talks about the INotifyPropertyChanged interface and how to use it for notifying data binding subscribers of changes in data sources. Data templates and selectors are also covered, as are value converters and data triggers. Examples include master-detail and sorting, grouping and filtering collections and binding trees and grids. Last it covers validation rules and error templates. Chapter 7 talks about the current trend in WPF development, the Model View View-Model (MVVM) framework. This is a well known pattern for connecting things interface to actions, and it is explained competently. A typical implementation is presented which also presents the command pattern used throughout WPF. A complete application using MVVM is presented from start to finish, including typical features such as undo. Style and layout is covered on chapter 8. Why/how to use styles, applying them automatically,  using the many types of triggers to change styles automatically, using Expression Blend behaviors and templates are all covered. Next chapter, 9, is about graphics and animations programming. It explains how to create shapes, transform common UI elements, apply special effects and perform simple animations. The following chapter, 10, is about creating custom controls, either by deriving from UserControl or from an existing control or framework element class, applying custom templates for changing the way the control looks. One useful example is a custom layout panel that arranges its children along a circumference. The final chapter, 11, is about multi-threading programming and how one can integrate it with WPF. Includes how to invoke methods and properties on WPF classes from threads other than the main UI, using background tasks and timers and even using the new C# 5.0 asynchronous operations. It’s an interesting book, like I said, mostly for newcomers. It provides a competent introduction to WPF, with examples that cover the most common scenarios and also give directions to more complex ones. I recommend it to everyone wishing to learn WPF.

    Read the article

  • Silverlight Cream for December 27, 2010 -- #1016

    - by Dave Campbell
    In this Issue: Sacha Barber, David Anson, Jesse Liberty, Shawn Wildermuth, Jeff Blankenburg(-2-), Martin Krüger, Ryan Alford(-2-), Michael Crump, Peter Kuhn(-2-). Above the Fold: Silverlight: "Part 4 of 4 : Tips/Tricks for Silverlight Developers" Michael Crump WP7: "Navigating with the WebBrowser Control on WP7" Shawn Wildermuth Shoutouts: John Papa posted that the open call is up for MIX11 presenters: Your Chance to Speak at MIX11 From SilverlightCream.com: Aspect Examples (INotifyPropertyChanged via aspects) If you're wanting to read a really in-depth discussion of aspect oriented programming (AOP), check out the article Sacha Barber has up at CodeProject discussing INPC via aspects. How to: Localize a Windows Phone 7 application that uses the Windows Phone Toolkit into different languages David Anson has a nice tutorial up on localizing your WP7 app, including using the Toolkit and controls such as DatePicker... remember we're talking localized Windows Phone From Scratch – Animation Part 1 Jesse Liberty continues in his 'From Scratch' series with this first post on WP7 Animation... good stuff, Jesse! Navigating with the WebBrowser Control on WP7 In building his latest WP7 app, Shawn Wildermuth ran into some obscure errors surrounding browser.InvokeScript. He lists the simple solution and his back, refresh, and forward button functionality for us. What I Learned In WP7 – Issue #7 In the time I was out, Jeff Blankenburg got ahead of me, so I'll catch up 2 at a time... in this number 7 he discusses making videos of your apps, links to the Learn Visual Studio series, and his new website What I Learned In WP7 – Issue #8 Jeff Blankenburg's number 8 is a very cool tip on using the return key on the keyboard to handle the loss of focus and handling of text typed into a textbox. Resize of a grid by using thumb controls Martin Krüger has a sample in the Expression Gallery of a grid that is resizable by using 'thumb controls' at the 4 corners... all source, so check it out! Silverlight 4 – Productivity Power Tools and EF4 Ryan Alford found a very interesting bug associated with EF4 and the Productivity Power Tools, and the way to get out of it is just weird as well. Silverlight 4 – Toolkit and Theming Ryan Alford also had a problem adding a theme from the Toolkit, and what all you might have to do to get around this one.... Part 4 of 4 : Tips/Tricks for Silverlight Developers. Michael Crump has part 4 of his series on Silverlight Development tips and tricks. This is numbers 16 through 20 and covers topics such as Version information, Using Lambdas, Specifying a development port, Disabling ChildWindow Close button, and XAML cleanup. The XML content importer and Windows Phone 7 Peter Kuhn wanted to use the XML content inporter with a WP7 app and ran into problems implementing the process and a lack of documentation as well... he pounded through it all and has a class he's sharing for loading sounds via XML file settings. WP7 snippet: analyzing the hyperlink button style In a second post, Peter Kuhn responds to a forum discussion about the styles for the hyperlink button in WP7 and why they're different than SL4 ... and styles-to-go to get all the hyperlink goodness you want... wrapped text, or even non-text content. 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

  • [EF + Oracle] Entities

    - by JTorrecilla
    Prologue Following with the Serie I started yesterday about Entity Framework with Oracle, Today I am going to start talking about Entities. What is an Entity? A Entity is an object of the EF model corresponding to a record in a DB table. For example, let’s see, in Image 1 we can see one Entity from our model, and in the second one we can see the mapping done with the DB. (Image 1) (Image 2) More in depth a Entity is a Class inherited from the abstract class “EntityObject”, contained by the “System.Data.Objects.DataClasses” namespace. At the same time, this class inherits from the following Class and interfaces: StructuralObject: It is an Abstract class that inherits from INotifyPropertyChanging and INotifyPropertyChanged interfaces, and it exposes the events that manage the Changes of the class, and the functions related to check the data types of the Properties from our Entity.  IEntityWithKey: Interface which exposes the Key of the entity. IEntityWithChangeTracker: Interface which lets indicate the state of the entity (Detached, Modified, Added…) IEntityWithRelationships: Interface which indicates the relations about the entity. Which is the Content of a Entity? A Entity is composed by: Properties, Navigation Properties and Methods. What is a Property? A Entity Property is an object that represents a column from the mapped table from DB. It has a data type equivalent in .Net Framework to the DB Type. When we create the EF model, VS, internally, create the code for each Entity selected in the Tables step, such all methods that we will see in next steps. For each property, VS creates a structure similar to: · Private variable with the mapped Data type. · Function with a name like On{Property_Name}Changing({dataType} value): It manages the event which happens when we try to change the value. · Function with a name like On{Property_Name}Change: It manages the event raised when the property has changed successfully. · Property with Get and Set methods: The Set Method manages the private variable and do the following steps: Raise Changing event. Report the Entity is Changing. Set the prívate variable. For it, Use the SetValidValue function of the StructuralObject. There is a function for each datatype, and the functions takes 2 params: the value, and if the prop allow nulls. Invoke that the entity has been successfully changed. Invoke the Changed event of the Prop. ReportPropertyChanging and ReportPropertyChanged events, let, respectively, indicate that there is pending changes in the Entity, and the changes have success correctly. While the ReportPropertyChanged is raised, the Track State of the Entity will be changed. What is a Navigation Property? Navigation Properties are a kind of property of the type: EntityCollection<TEntity>, where TEntity is an Entity type from the model related with the current one, it is said, is a set of record from a related table in the DB. The EntityCollection class inherits from: · RelatedEnd: There is an abstract class that give the functions needed to obtein the related objects. · ICollection<TEntity> · IEnumerable<TEntity> · IEnumerable · IListSource For the previous interfaces, I wish recommend the following post from Jose Miguel Torres. Navigation properties allow us, to get and query easily objects related with the Entity. Methods? There is only one method in the Entity object. “Create{Entity}”, that allow us to create an object of the Entity by sending the parameters needed to create it. Finally After this chapter, we know what is an Entity, how is related to the DB and the relation to other Entities. In following chapters, we will se CRUD operations(Create, Read, Update, Delete).

    Read the article

  • Silverlight ProgressBar issues with Binding

    - by Chris Skardon
    The ProgressBar pretty much does what it says on the tin, displays progress, in a bar form (well, by default anyhow). It’s pretty simple to use: <ProgressBar Minimum="0" Maximum="100" Value="50"/> Gives you a progress bar with 50% of it filled: Easy! But of course, we’re wanting to use binding to change the value, again, pretty easy, have a ViewModel with a ‘Value’ in it, and bind: <ProgressBar Minimum="0" Maximum="100" Value="{Binding Value}"/> Spiffy, and whilst we’re at it, why not bind the Maximum value as well – after all, we can’t be sure of the size of the progress, and it’s a pain to have to work out the percentage (when the progress bar can do it for us): <ProgressBar Minimum="0" Maximum="MaximumValue" Value="{Binding Value}"/> Right, this will work absolutely fine. Or will it??? On the face of it, it looks good, and testing it shows no issues, until at one point we go from: Maximum = 100; Value = 90; to Maximum=60; Value=50; On the face of it not unreasonable. The problem is more obvious if we look at the states of the properties after each set (initially Maximum is set at 1, Value = 0): Code Maximum Value Value < Maximum Maximum = 100; 100 0 True Value = 90; 100 90 True Maximum = 60; 60 90 False Value = 50; 60 50 True Everything is good until the Value is less than the Maximum, at this point the Progress Bar breaks. That’s right, it no longer updates itself, it will always look 100% full. The simple solution – always ensuring you set Value before Maximum is fine unless you’re using a ProgressBar in a less controlled environment – where for example you’re setting a ‘container’ with both values at the same time. The example I have is in a DataTemplate, I have a DataTemplate for a BusyIndicator, (specifically the BusyContentTemplate). The binding works this way: <BusyIndicator BusyContent="{Binding BusyContent}" BusyContentTemplate="{Binding ProgressTemplate}"/> With the template as the ProgressBar defined above… I was setting my BusyContent like this: BusyContent = content; aaaaaand finally, ‘content’ is a class: public class ContentClass : INotifyPropertyChanged { //Obviously this is properly implemented… public double Maximum { get;set;} public double Value { get;set;} } Soooo… As I was replacing the BusyContent wholesale, the order of the binding being set was outside of my control, so – how to go about it? Basically? Fudge it. Modify the ContentClass to include a method: public void Update(double value, double max) { Value = value; Maximum = max; } and change where the setting is to be: BusyContent.Update(content.Value, content.Maximum); Thereby getting the order correct.. Obvious really. Meh :|

    Read the article

  • Simple MVVM Walkthrough – Refactored

    - by Sean Feldman
    JR has put together a good introduction post into MVVM pattern. I love kick start examples that serve the purpose well. And even more than that I love examples that also can pass the real world projects check. So I took the sample code and refactored it slightly for a few aspects that a lot of developers might raise a brow. Michael has mentioned model (entity) visibility from view. I agree on that. A few other items that don’t settle are using property names as string (magical strings) and Saver class internal casting of a parameter (custom code for each Saver command). Fixing a property names usage is a straight forward exercise – leverage expressions. Something simple like this would do the initial job: class PropertyOf<T> { public static string Resolve(Expression<Func<T, object>> expression) { var member = expression.Body as MemberExpression; return member.Member.Name; } } With this, refactoring of properties names becomes an easy task, with confidence that an old property name string will not get left behind. An updated Invoice would look like this: public class Invoice : INotifyPropertyChanged { private int id; private string receiver; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public int Id { get { return id; } set { if (id != value) { id = value; OnPropertyChanged(PropertyOf<Invoice>.Resolve(x => x.Id)); } } } public string Receiver { get { return receiver; } set { receiver = value; OnPropertyChanged(PropertyOf<Invoice>.Resolve(x => x.Receiver)); } } } For the saver, I decided to change it a little so now it becomes a “view-model agnostic” command, one that can be used for multiple commands/view-models. Updated Saver code now accepts an action at construction time and executes that action. No more black magic internal class Command : ICommand { private readonly Action executeAction; public Command(Action executeAction) { this.executeAction = executeAction; } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { // no more black magic executeAction(); } } Change in InvoiceViewModel is instantiation of Saver command and execution action for the specific command. public ICommand SaveCommand { get { if (saveCommand == null) saveCommand = new Command(ExecuteAction); return saveCommand; } set { saveCommand = value; } } private void ExecuteAction() { DisplayMessage = string.Format("Thanks for creating invoice: {0} {1}", Invoice.Id, Invoice.Receiver); } This way internal knowledge of InvoiceViewModel remains in InvoiceViewModel and Command (ex-Saver) is view-model agnostic. Now the sample is not only a good introduction, but also has some practicality in it. My 5 cents on the subject. Sample code MvvmSimple2.zip

    Read the article

  • WPF MVVM UserControl Binding "Container", dispose to avoid memory leak.

    - by user178657
    For simplicity. I have a window, with a bindable usercontrol <UserControl Content="{Binding Path = BindingControl, UpdateSourceTrigger=PropertyChanged}"> I have two user controls, ControlA, and ControlB, Both UserControls have their own Datacontext ViewModel, ControlAViewModel and ControlBViewModel. Both ControlAViewModel and ControlBViewModel inh. from a "ViewModelBase" public abstract class ViewModelBase : DependencyObject, INotifyPropertyChanged, IDisposable........ Main window was added to IoC... To set the property of the Bindable UC, i do ComponentRepository.Resolve<MainViewWindow>().Bindingcontrol= new ControlA; ControlA, in its Datacontext, creates a DispatcherTimer, to do "somestuff".. Later on., I need to navigate elsewhere, so the other usercontrol is loaded into the container ComponentRepository.Resolve<MainViewWindow>().Bindingcontrol= new ControlB If i put a break point in the "someStuff" that was in ControlA's datacontext. The DispatcherTimer is still running... i.e. loading a new usercontrol into the bindable Usercontrol on mainwindow does not dispose/close/GC the DispatcherTimer that was created in the DataContext View Model... Ive looked around, and as stated by others, dispose doesnt get called because its not supposed to... :) Not all my usercontrols have DispatcherTimer, just a few that need to do some sort of "read and refresh" updates./. Should i track these DispatcherTimer objects in the ViewModelBase that all Usercontrols inh. and manually stop/dispose them everytime a new usercontrol is loaded? Is there a better way?

    Read the article

  • WPF - Binding an ObservableCollection Dependency Property within a UserControl

    - by John
    I have a control class DragGrid : Grid { ... } which inherits from the original grid and enables dragging and resizing its child elements. I need to bind a custom DP named WorkItemsProperty to an observable collection of type WorkItem (implements INotifyPropertyChanged). Each element in the grid is bound to a collection item. Whenever the user adds a new item dynamically at runtime (the items cannot be declared in XAML!), or deletes an item from that collection, the WorkItems DP on the DragGrid should be updated, and the children in the grid (where each child represents a WorkItem collection item). My question is how does the DP notify the control about which child element in the grid must be removed, changed ('change' means user dragged an element, or resized it with the mouse) or added, and how would I identify which one of the existing children is the one that needs to be deleted or changed. I understand that this is where the DependencyPropertyChangedCallback comes in. But that only gets called when the DP property is set anew, not when something inside the collection changes (like add, remove item). So in the end, does the DragGrid control somehow need to subscribe to the CollectionChanged event? At what point would I hook up the event handler for that?

    Read the article

  • Binding "Text-Property" of a derived textbox to another textbox doesn´t work

    - by Jehof
    Hello, i have a class 'MyTextBox' that derives from the default TextBox in Silverlight. This class currently contains no additional code. I set up a binding in xaml to bind the Text-Property of MyTextbox to another Textbox to reflect the input made in the Textbox. The effect is that MyTextBox doesn´t update and not display the text of the other Textbox. Additional i made an equal binding for a normal Textbox. And this works. Here´s the XAML for the bindings. <UserControl x:Class="Silverlight.Sample.Dummy" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:Sample" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <StackPanel x:Name="LayoutRoot" Background="White"> <TextBox Height="23" x:Name="textBox2" Width="120" /> <TextBox Text="{Binding ElementName=textBox2, Path=Text, Mode=TwoWay}" Width="120" /> <my:NumberTextBox Width="120" Text="{Binding ElementName=textBox2, Path=Text, Mode=OneWay}" /> </StackPanel> Is there something special to set for binding, when i derive from a control. PS: I tried a binding to a dummy object with INotifyPropertyChanged and set it as DataContext for the existing Textboxes. This test works as expected and my derived textbox gets updated.

    Read the article

  • How To Raise Property Changed events on a Dependency Property?

    - by Muad'Dib
    OK, so I have this control with two properties. One of these is a DependencyProperty, the other is an "alias" to the first one. What I need to be able to do is raise the PropertyChanged event for the second one (the alias) when the first one is changed. NOTE: I am using DependencyObjects, not INotifyPropertyChanged (tried that, didn't work because my control is a sub-classed ListView) something like this..... protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { base.OnPropertyChanged(e); if (e.Property == MyFirstProperty) { RaiseAnEvent( MySecondProperty ); /// what is the code that would go here? } } If I were using an INotify I could do like this... public string SecondProperty { get { return this.m_IconPath; } } public string IconPath { get { return this.m_IconPath; } set { if (this.m_IconPath != value) { this.m_IconPath = value; this.SendPropertyChanged("IconPath"); this.SendPropertyChanged("SecondProperty"); } } } where I can raise PropertyChanged events on multiple properties from one setter. I need to be able to do the same thing, only using DependencyProperties.

    Read the article

  • C++ compiler errors in xamltypeinfo.g.cpp

    - by Richard Banks
    I must be missing something obvious but I'm not sure what. I've created a blank C++ metro app and I've just added a model that I will bind to in my UI however I'm getting a range of compiler warnings related to xamltypeinfo.g.cpp and I'm not sure what I've missed. My header file looks like this: #pragma once #include "pch.h" #include "MyColor.h" using namespace Platform; namespace CppDataBinding { [Windows::UI::Xaml::Data::Bindable] public ref class MyColor sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged { public: MyColor(); ~MyColor(); virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged; property Platform::String^ RedValue { Platform::String^ get() { return _redValue; } void set(Platform::String^ value) { _redValue = value; RaisePropertyChanged("RedValue"); } } protected: void RaisePropertyChanged(Platform::String^ name); private: Platform::String^ _redValue; }; } and my cpp file looks like this: #include "pch.h" #include "MyColor.h" using namespace CppDataBinding; MyColor::MyColor() { } MyColor::~MyColor() { } void MyColor::RaisePropertyChanged(Platform::String^ name) { if (PropertyChanged != nullptr) { PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs(name)); } } Nothing too tricky, but when I compile I get errors in xamltypeinfo.g.cpp indicating that MyColor is not defined in CppDataBinding. The relevant generated code looks like this: if (typeName == "CppDataBinding.MyColor") { userType = ref new XamlUserType(this, typeName, GetXamlTypeByName("Object")); userType->Activator = ref new XamlTypeInfo::InfoProvider::Activator( []() -> Platform::Object^ { return ref new CppDataBinding::MyColor(); }); userType->AddMemberName("RedValue", "CppDataBinding.MyColor.RedValue"); userType->SetIsBindable(); xamlType = userType; } If I remove the Bindable attribute from MyColor the code compiles. Can someone tell me what blindingly obvious thing I've missed so I can give myself a facepalm and fix the problem?

    Read the article

  • WPF Datagrid set the column values only when the row is left

    - by Noam
    Hello I have a simple class. When I use it in winforms binding, whenever I change a value of a cell and leave the cell, the property immediately get changed. Using WPF Datagrid, whenever i change a value of a cell, the property gets set only after I leave the row. That is problematic for me. What am I doing wrong? Here is my code: public class MyClass : IEditableObject, INotifyPropertyChanged { string _name, _lastName; public string Name { get { return _name; } set { _name = value; _lastName = value + " xxx"; OnPropertyChanged("LastName"); MessageBox.Show("Test"); } } private void OnPropertyChanged(string p) { var x = new PropertyChangedEventArgs(p); if (PropertyChanged != null) PropertyChanged(this, x); } public string LastName { get { return _lastName; } set { _lastName = value; } } public void BeginEdit() { } public void CancelEdit() { } public void EndEdit() { } public event PropertyChangedEventHandler PropertyChanged; } public class myBindingList : BindingList<MyClass> { public myBindingList() { AllowNew = true; Add(new MyClass { Name = "noam" }); Add(new MyClass { Name = "yael" }); } }

    Read the article

  • WPF MVVM ViewModel constructor designmode

    - by Snake
    Right, I've got a main wpf window: <Window x:Class="NorthwindInterface.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ViewModels="clr-namespace:NorthwindInterface.ViewModels" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <ViewModels:MainViewModel /> </Window.DataContext> <ListView ItemsSource="{Binding Path=Customers}"> </ListView> </Window> And the MainViewModel is this: class MainViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged = delegate { }; public MainViewModel() { Console.WriteLine("test"); using (NorthwindEntities northwindEntities = new NorthwindEntities()) { this.Customers = (from c in northwindEntities.Customers select c).ToList(); } } public List<Customer> Customers { get;private set; } Now the problem is that in designermode I can't see my MainViewModel, it highlights it saying that it can't create an instance of the MainViewModel. It is connecting to a database. That is why (when I comment the code the problem is solved). But I don't want that. Any solutions on best practices around this?

    Read the article

  • Binding to WPF ViewModel properties

    - by MartinHN
    I'm just playing around with WPF and MVVM, and I have made a simple app that displays a Rectangle that changes color whenever Network availability changes. But when that happens, I get this error: Cannot use a DependencyObject that belongs to a different thread than its parent Freezable. Code XAML <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="400" Width="600"> <DockPanel LastChildFill="True"> <Rectangle x:Name="networkStatusRectangle" Width="200" Height="200" Fill="{Binding NetworkStatusColor}" /> </DockPanel> </Window> Code-behind using System.Windows; using WpfApplication1.ViewModels; namespace WpfApplication1 { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); DataContext = new NetworkViewModel(); } } } ViewModel using System.ComponentModel; using System.Net.NetworkInformation; using System.Windows.Media; namespace WpfApplication1.ViewModels { public class NetworkViewModel : INotifyPropertyChanged { private Brush _NetworkStatusColor; public Brush NetworkStatusColor { get { return _NetworkStatusColor; } set { _NetworkStatusColor = value; NotifyOfPropertyChange("NetworkStatusColor"); } } public NetworkViewModel() { NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged); } protected void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) { if (e.IsAvailable) { this.NetworkStatusColor = new SolidColorBrush(Colors.Green); } else { this.NetworkStatusColor = new SolidColorBrush(Colors.Red); } } public event PropertyChangedEventHandler PropertyChanged = delegate { }; public void NotifyOfPropertyChange(string propertyName) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } I assume that I should change the NetworkStatusColor property by invoking something?

    Read the article

  • Can a WPF ComboBox display alternative text when its selection is null?

    - by Garth T Kidd
    G'day! I want my WPF ComboBox to display some alternative text when its data-bound selection is null. The view model has the expected properties: public ThingoSelectionViewModel : INotifyPropertyChanged { public ThingoSelectionViewModel(IProvideThingos) { this.Thingos = IProvideThingos.GetThingos(); } public ObservableCollection<Thingo> Thingos { get; set; } public Thingo SelectedThingo { get { return this.selectedThingo; } set { // set this.selectedThingo and raise the property change notification } // ... } The view has XAML binding to the view model in the expected way: <ComboBox x:Name="ComboboxDrive" SelectedItem="{Binding Path=SelectedThingo}" IsEditable="false" HorizontalAlignment="Left" MinWidth="100" IsReadOnly="false" Style="{StaticResource ComboboxStyle}" Grid.Column="1" Grid.Row="1" Margin="5" SelectedIndex="0"> <ComboBox.ItemsSource> <CompositeCollection> <ComboBoxItem IsEnabled="False">Select a thingo</ComboBoxItem> <CollectionContainer Collection="{Binding Source={StaticResource Thingos}}" /> </CompositeCollection> </ComboBox.ItemsSource> </ComboBox> The ComboBoxItem wedged into the top is a way to get an extra item at the top. It's pure chrome: the view model stays pure and simple. There's just one problem: the users want "Select a thingo" displayed whenever the ComboBox' selection is null. The users do not want a thingo selected by default. They want to see a message telling them to select a thingo. I'd like to avoid having to pollute the viewmodel with a ThingoWrapper class with a ToString method returning "Select a thingo" if its .ActualThingo property is null, wrapping each Thingo as I populate Thingos, and figuring out some way to prevent the user from selecting the nulled Thingo. Is there a way to display "Select a thingo" within the ComboBox' boundaries using pure XAML, or pure XAML and a few lines of code in the view's code-behind class?

    Read the article

  • C# Thread-safe Extension Method

    - by Wonko the Sane
    Hello All, I may be waaaay off, or else really close. Either way, I'm currently SOL. :) I want to be able to use an extension method to set properties on a class, but that class may (or may not) be updated on a non-UI thread, and derives from a class the enforces updates to be on the UI thread (which implements INotifyPropertyChanged, etc). I have a class defined something like this: public class ClassToUpdate : UIObservableItem { private readonly Dispatcher mDispatcher = Dispatcher.CurrentDispatcher; private Boolean mPropertyToUpdate = false; public ClassToUpdate() : base() { } public Dispatcher Dispatcher { get { return mDispatcher; } } public Boolean PropertyToUpdate { get { return mPropertyToUpdate; } set { SetValue("PropertyToUpdate", ref mPropertyToUpdate, value; } } } I have an extension method class defined something like this: static class ExtensionMethods { public static IEnumerable<T> SetMyProperty<T>(this IEnumerable<T> sourceList, Boolean newValue) { ClassToUpdate firstClass = sourceList.FirstOrDefault() as ClassToUpdate; if (firstClass.Dispatcher.Thread.ManagedThreadId != System.Threading.Thread.CurrentThread.ManagedThreadId) { // WHAT GOES HERE? } else { foreach (var classToUpdate in sourceList) { (classToUpdate as ClassToUpdate ).PropertyToUpdate = newValue; yield return classToUpdate; } } } } Obviously, I'm looking for the "WHAT GOES HERE" in the extension method. Thanks, wTs

    Read the article

  • Threadsafe binding with DispatcherObject.CheckAccess()

    - by maffe
    Hi, according to this, I can achieve threadsafety with large overhead. I wrote the following class and use it. It works fine. public abstract class BindingBase : DispatcherObject, INotifyPropertyChanged, INotifyPropertyChanging { private string _displayName; private const string NameDisplayName = "DisplayName"; /// /// The display name for the gui element which bound this instance. It can be used for localization. /// public string DisplayName { get { return _displayName; } set { NotifyPropertyChanging(NameDisplayName); _displayName = value; NotifyPropertyChanged(NameDisplayName); } } protected BindingBase() {} protected BindingBase(string displayName) { DisplayName = displayName; } public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangingEventHandler PropertyChanging; protected void NotifyPropertyChanged(string name) { if (PropertyChanged == null) return; if (CheckAccess()) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name)); else Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (() = NotifyPropertyChanged(name))); } protected void NotifyPropertyChanging(string name) { if (PropertyChanging == null) return; if (CheckAccess()) PropertyChanging.Invoke(this, new PropertyChangingEventArgs(name)); else Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (() = NotifyPropertyChanging(name))); } } So is there a reason, why I've never found something like that? Are there any issues I should be aware off? Regards

    Read the article

  • XAML Binding to complex value objects

    - by Gus
    I have a complex value object class that has 1) a number or read-only properties; 2) a private constructor; and 3) a number of static singleton instance properties [so the properties of a ComplexValueObject never change and an individual value is instantiated once in the application's lifecycle]. public class ComplexValueClass { /* A number of read only properties */ private readonly string _propertyOne; public string PropertyOne { get { return _propertyOne; } } private readonly string _propertyTwo; public string PropertyTwo { get { return _propertyTwo; } } /* a private constructor */ private ComplexValueClass(string propertyOne, string propertyTwo) { _propertyOne = propertyOne; _propertyTwo = PropertyTwo; } /* a number of singleton instances */ private static ComplexValueClass _complexValueObjectOne; public static ComplexValueClass ComplexValueObjectOne { get { if (_complexValueObjectOne == null) { _complexValueObjectOne = new ComplexValueClass("string one", "string two"); } return _complexValueObjectOne; } } private static ComplexValueClass _complexValueObjectTwo; public static ComplexValueClass ComplexValueObjectTwo { get { if (_complexValueObjectTwo == null) { _complexValueObjectTwo = new ComplexValueClass("string three", "string four"); } return _complexValueObjectTwo; } } } I have a data context class that looks something like this: public class DataContextClass : INotifyPropertyChanged { private ComplexValueClass _complexValueClass; public ComplexValueClass ComplexValueObject { get { return _complexValueClass; } set { _complexValueClass = value; PropertyChanged(this, new PropertyChangedEventArgs("ComplexValueObject")); } } } I would like to write a XAML binding statement to a property on my complex value object that updates the UI whenever the entire complex value object changes. What is the best and/or most concise way of doing this? I have something like: <Object Value="{Binding ComplexValueObject.PropertyOne}" /> but the UI does not update when ComplexValueObject as a whole changes.

    Read the article

  • WPF Toolkit: Nullable object must have a value

    - by Via Lactea
    Hi All, I am trying to create some line charts from a dataset and getting an error (WPF+WPF Toolkit + C#): Nullable object must have a value Here is a code that I use to add some data points to the chart: ObservableCollection points = new ObservableCollection(); foreach (DataRow dr in dc.Tables[0].Rows) { points.Add(new VelChartPoint() { Label = dr[0].ToString(), Value = double.Parse(dr[1].ToString()) }); } Here is a class VelChartPoint public class VelChartPoint : VelObject, INotifyPropertyChanged { public DateTime Date { get; set; } public string Label { get; set; } private double _Value; public double Value { get { return _Value; } set { _Value = value; var handler = PropertyChanged; if (null != handler) { handler.Invoke(this, new PropertyChangedEventArgs("Value")); } } } public string FieldName { get; set; } public event PropertyChangedEventHandler PropertyChanged; public VelChartPoint() { } } So the problem occures in this part of the code points.Add(new VelChartPoint { Name = dc.Tables[0].Rows[0][0].ToString(), Value = double.Parse(dc.Tables[0].Rows[0][1].ToString()) } ); I've made some tests, here are some results i've found out. This part of code does'nt work for me: string[] labels = new string[] { "label1", "label2", "label3" }; foreach (string label in labels) { points.Add(new VelChartPoint { Name = label, Value = 500.0 } ); } But this one works fine: points.Add(new VelChartPoint { Name = "LabelText", Value = double.Parse(dc.Tables[0].Rows[0][1].ToString()) } ); Please, help me to solve this error.

    Read the article

  • ViewModel updates after Model server roundtrip

    - by Pavel Savara
    I have stateless services and anemic domain objects on server side. Model between server and client is POCO DTO. The client should become MVVM. The model could be graph of about 100 instances of 20 different classes. The client editor contains diverse tab-pages all of them live-connected to model/viewmodel. My problem is how to propagate changes after server round-trip nice way. It's quite easy to propagate changes from ViewModel to DTO. For way back it would be possible to throw away old DTO and replace it whole with new one, but it will cause lot of redrawing for lists/DataTemplates. I could gather the server side changes and transmit them to client side. But the names of fields changed would be domain/DTO specific, not ViewModel specific. And the mapping seems nontrivial to me. If I should do it imperative way after round-trip, it would break SOC/modularity of viewModels. I'm thinking about some kind of mapping rule engine, something like automappper or emit mapper. But it solves just very plain use-cases. I don't see how it would map/propagate/convert adding items to list or removal. How to identify instances in collections so it could merge values to existing instances. As well it should propagate validation/error info. Maybe I should implement INotifyPropertyChanged on DTO and try to replay server side events on it ? And then bind ViewModel to it ? Would binding solve the problems with collection merges nice way ? Is EventAgregator from PRISM useful for that ? Is there any event record-replay component ? Is there better client side pattern for architecture with server side logic ?

    Read the article

  • PostSharp when using DataContractSerializer?

    - by Dan Bryant
    I have an Aspect that implements INotifyPropertyChanged on a class. The aspect includes the following: [OnLocationSetValueAdvice, MethodPointcut("SelectProperties")] public void OnPropertySet(LocationInterceptionArgs args) { var currentValue = args.GetCurrentValue(); bool alreadyEqual = (currentValue == args.Value); // Call the setter args.ProceedSetValue(); // Invoke method OnPropertyChanged (ours, the base one, or the overridden one). if (!alreadyEqual) OnPropertyChangedMethod.Invoke(args.Location.Name); } This works fine when I instantiate the class normally, but I run into problems when I deserialize the class using a DataContractSerializer. This bypasses the constructor, which I'm guessing interferes with the way that PostSharp sets itself up. This ends up causing a NullReferenceException in an intercepted property setter, but before it has called the custom OnPropertySet, so I'm guessing it interferes with setting up the LocationInterceptionArgs. Has anyone else encountered this problem? Is there a way I can work around it? I did some more research and discovered I can fix the issue by doing this: [OnDeserializing] private void OnDeserializing(StreamingContext context) { AspectUtilities.InitializeCurrentAspects(); } I thought, okay, that's not too bad, so I tried to do this in my Aspect: private IEnumerable<MethodInfo> SelectDeserializing(Type type) { return type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where( t => t.IsDefined(typeof (OnDeserializingAttribute), false)); } [OnMethodEntryAdvice, MethodPointcut("SelectDeserializing")] public void OnMethodEntry(MethodExecutionArgs args) { AspectUtilities.InitializeCurrentAspects(); } Unfortunately, even though it intercepts the method properly, it doesn't work. I'm thinking the call to InitializeCurrentAspects isn't getting transformed properly, since it's now inside the Aspect rather than directly inside the aspect-enhanced class. Is there a way I can cleanly automate this so that I don't have to worry about calling this on every class that I want to have the Aspect?

    Read the article

  • wpf c# databinding on object

    - by Enriquev
    Hello, say I have this control: public partial class bloc999 : UserControl { bloc999Data mainBlock = new bloc999Data(); public bloc999() { InitializeComponent(); mainBlock.txtContents = "100"; base.DataContext = mainBlock; } } in the xaml: <TextBox Margin="74,116,106,0" Name="txtContents" Text="{Binding Path=txtContents, UpdateSourceTrigger=PropertyChanged,Mode = TwoWay}" /> <TextBox Margin="74,145,106,132" Name="txtContents2" Text="{Binding Path=txtContents2, UpdateSourceTrigger=PropertyChanged,Mode = TwoWay}" /> Then I have this class: public class bloc999Data : INotifyPropertyChanged { string _txtContents; string _txtContents2; public event PropertyChangedEventHandler PropertyChanged; void NotifyPropertyChanged(string propName) { if (this.PropertyChanged != null) this.PropertyChanged( this, new PropertyChangedEventArgs(propName)); } public string txtContents2 { get { return this._txtContents2; } set { if (int.Parse(value) > int.Parse(this._txtContents)) { this._txtContents2 = "000"; } else this._txtContents2 = value; NotifyPropertyChanged("txtContents2"); } } public string txtContents { get { return this._txtContents; } set { this._txtContents = value; NotifyPropertyChanged("txtContents"); } } } Ok now say I have A button on the form and I do this in the code: mainBlock.txtContents2 = "7777777"; It puts 000 in the textbox, but If i just type in manually, in the textbox (txtContents2, the setter code is called but for some reason the textboxes value does not change, the instance value does change. help?

    Read the article

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