Search Results

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

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

  • WPF: Binding to ListBoxItem.IsSelected doesn't work for off-screen items

    - by Qwertie
    In my program I have a set of view-model objects to represent items in a ListBox (multi-select is allowed). The viewmodel has an IsSelected property that I would like to bind to the ListBox so that selection state is managed in the viewmodel rather than in the listbox itself. However, apparently the ListBox doesn't maintain bindings for most of the off-screen items, so in general the IsSelected property is not synchronized correctly. Here is some code that demonstrates the problem. First XAML: <StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock>Number of selected items: </TextBlock> <TextBlock Text="{Binding NumItemsSelected}"/> </StackPanel> <ListBox ItemsSource="{Binding Items}" Height="200" SelectionMode="Extended"> <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="IsSelected" Value="{Binding IsSelected}"/> </Style> </ListBox.ItemContainerStyle> </ListBox> <Button Name="TestSelectAll" Click="TestSelectAll_Click">Select all</Button> </StackPanel> C# Select All handler: private void TestSelectAll_Click(object sender, RoutedEventArgs e) { foreach (var item in _dataContext.Items) item.IsSelected = true; } C# viewmodel: public class TestItem : NPCHelper { TestDataContext _c; string _text; public TestItem(TestDataContext c, string text) { _c = c; _text = text; } public override string ToString() { return _text; } bool _isSelected; public bool IsSelected { get { return _isSelected; } set { _isSelected = value; FirePropertyChanged("IsSelected"); _c.FirePropertyChanged("NumItemsSelected"); } } } public class TestDataContext : NPCHelper { public TestDataContext() { for (int i = 0; i < 200; i++) _items.Add(new TestItem(this, i.ToString())); } ObservableCollection<TestItem> _items = new ObservableCollection<TestItem>(); public ObservableCollection<TestItem> Items { get { return _items; } } public int NumItemsSelected { get { return _items.Where(it => it.IsSelected).Count(); } } } public class NPCHelper : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void FirePropertyChanged(string prop) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } Two separate problems can be observed. If you click the first item and then press Shift+End, all 200 items should be selected; however, the heading reports that only 21 items are selected. If you click "Select all" then all items are indeed selected. If you then click an item in the ListBox you would expect the other 199 items to be deselected, but this does not happen. Instead, only the items that are on the screen (and a few others) are deselected. All 199 items will not be deselected unless you first scroll through the list from beginning to end (and even then, oddly enough, it doesn't work if you perform scrolling with the little scroll box). My questions are: Can someone explain precisely why this occurs? Can I avoid or work around the problem?

    Read the article

  • Implementing a generic repository for WCF data services

    - by cibrax
    The repository implementation I am going to discuss here is not exactly what someone would call repository in terms of DDD, but it is an abstraction layer that becomes handy at the moment of unit testing the code around this repository. In other words, you can easily create a mock to replace the real repository implementation. The WCF Data Services update for .NET 3.5 introduced a nice feature to support two way data bindings, which is very helpful for developing WPF or Silverlight based application but also for implementing the repository I am going to talk about. As part of this feature, the WCF Data Services Client library introduced a new collection DataServiceCollection<T> that implements INotifyPropertyChanged to notify the data context (DataServiceContext) about any change in the association links. This means that it is not longer necessary to manually set or remove the links in the data context when an item is added or removed from a collection. Before having this new collection, you basically used the following code to add a new item to a collection. Order order = new Order {   Name = "Foo" }; OrderItem item = new OrderItem {   Name = "bar",   UnitPrice = 10,   Qty = 1 }; var context = new OrderContext(); context.AddToOrders(order); context.AddToOrderItems(item); context.SetLink(item, "Order", order); context.SaveChanges(); Now, thanks to this new collection, everything is much simpler and similar to what you have in other ORMs like Entity Framework or L2S. Order order = new Order {   Name = "Foo" }; OrderItem item = new OrderItem {   Name = "bar",   UnitPrice = 10,   Qty = 1 }; order.Items.Add(item); var context = new OrderContext(); context.AddToOrders(order); context.SaveChanges(); In order to use this new feature, you first need to enable V2 in the data service, and then use some specific arguments in the datasvcutil tool (You can find more information about this new feature and how to use it in this post). DataSvcUtil /uri:"http://localhost:3655/MyDataService.svc/" /out:Reference.cs /dataservicecollection /version:2.0 Once you use those two arguments, the generated proxy classes will use DataServiceCollection<T> rather than a simple ObjectCollection<T>, which was the default collection in V1. There are some aspects that you need to know to use this feature correctly. 1. All the entities retrieved directly from the data context with a query track the changes and report those to the data context automatically. 2. A entity created with “new” does not track any change in the properties or associations. In order to enable change tracking in this entity, you need to do the following trick. public Order CreateOrder() {   var collection = new DataServiceCollection<Order>(this.context);   var order = new Order();   collection.Add(order);   return order; } You basically need to create a collection, and add the entity to that collection with the “Add” method to enable change tracking on that entity. 3. If you need to attach an existing entity (For example, if you created the entity with the “new” operator rather than retrieving it from the data context with a query) to a data context for tracking changes, you can use the “Load” method in the DataServiceCollection. var order = new Order {   Id = 1 }; var collection = new DataServiceCollection<Order>(this.context); collection.Load(order); In this case, the order with Id = 1 must exist on the data source exposed by the Data service. Otherwise, you will get an error because the entity did not exist. These cool extensions methods discussed by Stuart Leeks in this post to replace all the magic strings in the “Expand” operation with Expression Trees represent another feature I am going to use to implement this generic repository. Thanks to these extension methods, you could replace the following query with magic strings by a piece of code that only uses expressions. Magic strings, var customers = dataContext.Customers .Expand("Orders")         .Expand("Orders/Items") Expressions, var customers = dataContext.Customers .Expand(c => c.Orders.SubExpand(o => o.Items)) That query basically returns all the customers with their orders and order items. Ok, now that we have the automatic change tracking support and the expression support for explicitly loading entity associations, we are ready to create the repository. The interface for this repository looks like this,public interface IRepository { T Create<T>() where T : new(); void Update<T>(T entity); void Delete<T>(T entity); IQueryable<T> RetrieveAll<T>(params Expression<Func<T, object>>[] eagerProperties); IQueryable<T> Retrieve<T>(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] eagerProperties); void Attach<T>(T entity); void SaveChanges(); } The Retrieve and RetrieveAll methods are used to execute queries against the data service context. While both methods receive an array of expressions to load associations explicitly, only the Retrieve method receives a predicate representing the “where” clause. The following code represents the final implementation of this repository.public class DataServiceRepository: IRepository { ResourceRepositoryContext context; public DataServiceRepository() : this (new DataServiceContext()) { } public DataServiceRepository(DataServiceContext context) { this.context = context; } private static string ResolveEntitySet(Type type) { var entitySetAttribute = (EntitySetAttribute)type.GetCustomAttributes(typeof(EntitySetAttribute), true).FirstOrDefault(); if (entitySetAttribute != null) return entitySetAttribute.EntitySet; return null; } public T Create<T>() where T : new() { var collection = new DataServiceCollection<T>(this.context); var entity = new T(); collection.Add(entity); return entity; } public void Update<T>(T entity) { this.context.UpdateObject(entity); } public void Delete<T>(T entity) { this.context.DeleteObject(entity); } public void Attach<T>(T entity) { var collection = new DataServiceCollection<T>(this.context); collection.Load(entity); } public IQueryable<T> Retrieve<T>(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] eagerProperties) { var entitySet = ResolveEntitySet(typeof(T)); var query = context.CreateQuery<T>(entitySet); foreach (var e in eagerProperties) { query = query.Expand(e); } return query.Where(predicate); } public IQueryable<T> RetrieveAll<T>(params Expression<Func<T, object>>[] eagerProperties) { var entitySet = ResolveEntitySet(typeof(T)); var query = context.CreateQuery<T>(entitySet); foreach (var e in eagerProperties) { query = query.Expand(e); } return query; } public void SaveChanges() { this.context.SaveChanges(SaveChangesOptions.Batch); } } For instance, you can use the following code to retrieve customers with First name equal to “John”, and all their orders in a single call. repository.Retrieve<Customer>(    c => c.FirstName == “John”, //Where    c => c.Orders.SubExpand(o => o.Items)); In case, you want to have some pre-defined queries that you are going to use across several places, you can put them in an specific class. public static class CustomerQueries {   public static Expression<Func<Customer, bool>> LastNameEqualsTo(string lastName)   {     return c => c.LastName == lastName;   } } And then, use it with the repository. repository.Retrieve<Customer>(    CustomerQueries.LastNameEqualsTo("foo"),    c => c.Orders.SubExpand(o => o.Items));

    Read the article

  • CodePlex Daily Summary for Wednesday, March 17, 2010

    CodePlex Daily Summary for Wednesday, March 17, 2010New Projectschaosreader: A simple RSS reader.CRM 4.0 Customization GUID Update: The CRM 4.0 customization GUID update is an open source C# console application that automatically replaces GUID values in your exported workflow cu...DotNetNuke® Skin Bright: A DotNetNuke Design Challenge skin package submitted to the "Modern Business" category by Noel Jerke of SiteToolset. This simple and clean business...DotNetNuke® Skin Go: A DotNetNuke Design Challenge skin package submitted to the "Modern Business" category by DnnGo Corporation. The skin uses web standard DIV+CSS tec...DotNetNuke® Skin J10blend: A DotNetNuke Design Challenge skin package submitted to the "Out of the box" category by Timthy Maler of 2M Studio Design. J10-Black v01.00.00 inc...DotNetNuke® Skin Recipe: A DotNetNuke Design Challenge skin package submitted to the "Standards" category by dnnprofis.at. For mobile devices the skin changes to a mobile...DotNetNuke® Skin SpaceSmurfs: A DotNetNuke Design Challenge skin package submitted to the "Personal" category by Eric Johnson of Personify Design. This fun personal skin was ins...ERDOS6 - Web: A Web Project about ERDOS 6Flickrlight: Flickrlight is a personal fun project out of love of Flickr and Silverlight. You can experience it here: http://www.flickrlight.net.GsGrid: Extracting data from Gaussian grid file and grid file calculationiLocator: iLocator is a collaborative educational mapping game for children developed on Microsoft Surface. This game encourages players to collaborate with ...Javascript CallObject SOAP AJAX Helper: CallObject is a Javascript based AJAX helper, it facilitates wrapping of basic soap calls (as long as simple data types are used), asynchronous ret...kbTrainer: kbTrainer is a simple to use HTML application for typing speed training. A lot of features completed in basic. 2 learning keywords layouts -- engli...Laboratório de Engenharia de Software - Projeto: Criado para estudar e aplicar novas tecnologias web.Maxilds Powershell Scripts: Repo of my powershell scriptsNamespacifier: Namespacifier is a C#.NET library and console application to fix XML documents containing multiple default namespaces. It gives prefixes to defaul...OData SDK for Objective-C: This is a CTP of the OData SDK for Objective-C. The library targets iPhone devices and Mac OS X and it is designed to facilitate the connection wit...Open Data App Framework (ODAF): The Open Data Application Framework (ODAF) is a framework that allows cities to easily map existing civic Open Data landmarks, and allow users to r...QuickieB2B: QuickieB2B is web application which main target is to provide quick info about products. It's designed for small companies who have a big number of...RayView: Rayview is an easy-to-use Raytracing-Framework based on Microsoft XNA.Robotics Studio application to navigate Lego Mindstorms robot through labyrinth: A project for Software Systems Analysis and Design Tools subject at the Kaunas University of Technology. The main point of the project is to code L...SharePoint Icon Integration: SharePoint Icon Integration makes it easier for SharePoint Administrators / Developers to add a icon (pdf) to the SharePoint farm. You will no long...TestVersion: Testing VersionieringTimecard: SoftSource Timecard project.T-shirt Cannon: So the Coding4Fun team had two weeks to build two robots able to drive, aim, and shoot t-shirts with a Windows Phone during a MIX10 Keynote demo of...USTF: This project is a bit secretive right now.Windows Azure Command-line Tools for PHP Developers: The “Windows Azure Command-line tools for PHP” provide a command-line experience to developers who wish to develop, package, and deploy PHP applic...New ReleasesCaramel Engine: CaramelEngine Alpha Build 0.0.0.1a: This is an early alpha release of the Engine and it's functionality. Be sure to have the using CaramelEngine statement. This release is for people...Coot: Preview: Basic preview On the first use you have to click Create New Session and Login. After this you can just click Screen Saver each time. Settings sho...CycleMania Starter Kit EAP - ASP.NET 4.0 Problem - Design - Solution: Cyclemania 0.08.32: The latest alpha release.DeepZoomContainer, Expanded DeepZoom for Silverlight & Windows Phone 7 Series: Release ver. 1.20 for Windows Phone 7 Series: SolutionMerge PathAnimation solution into one MouseWheel elimination PathAnimationWP7 Port DeepZoomContainerProject rebuilt for WP7 support De...Desktop Google Reader: 1.3 (the social release): NewsSharing Liking Mail item Labels / Tags Send to Twitter Read It Later http://readitlaterlist.com/ Instapaper http://www.instapaper.com/ Favicons...DotNetNuke® Blog: 04.00.00 RC 2: PLEASE NOTE: Please do not upgrade previous version of the Beta releases - please start from 03.05.01 This is a RELEASE CANDIDATE, and as such ...DotNetNuke® Community Edition: 05.03.00: New FeaturesTemplated User Profiles - User profile pages are now publicly viewable Photo field in User Profile - Users can upload a photo to thei...DotNetNuke® Skin Bright: Bright Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Modern Business" category by Noel Jerke of SiteToolset. This simple and clean business...DotNetNuke® Skin Go: Go Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Modern Business" category by DnnGo Corporation. The skin uses web standard DIV+CSS tec...DotNetNuke® Skin J10blend: J10 Blend Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Out of the box" category by Timthy Maler of 2M Studio Design. J10-Black v01.00.00 incl...DotNetNuke® Skin Recipe: Recipe Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Standards" category by dnnprofis.at. For mobile devices the skin changes to a mobile f...DotNetNuke® Skin SpaceSmurfs: Space Smurfs Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Personal" category by Eric Johnson of Personify Design. This fun personal skin was ins...Dynamo: Dynamo v0.1 Beta: The following is included: Dynamo dlls Antlr dlls Hello world Simple Plugin example Application Dependency injection Singleton Managment ...ExtremeML: ExtremeML v1.0 Beta 1: Timed to accompany the RTM release of the OpenXML SDK v2.0, this is the first Beta release of ExtremeML (it was previously classified as a preview ...Family Tree Analyzer: Version 1.1.1.1: Version 1.1.1.1 Lots of Gedcom parsing fixes it should crash a whole lot less often and tolerate more "interesting" or "quirky" Gedcom entries. Add...Family Tree Analyzer: Version 1.2.0.1: Version 1.2.0.1 Added option to treat residence facts as Census Facts IGI Search now permits default country selection ie: what to use if it doesn...Flickrlight: Flickrlight: Current release is for idea sharing. There are not many design patterns being used. Please bare with the mess. :-) In order to run the applicat...Gherkin editor: Alpha 0.1: Most of the code at this point is the same as the Avalon.Sample from code project, just changed the name, removed extra languages and added syntax ...GsGrid: gsgrid1.6.4: gsgrid1.6.4GsGrid: gsgrid1.6.4-src: gsgrid1.6.4-srcHTML Template Repeater Module: Version 01.00.02: GeneralThe HTML Template Repeater Module is a direct replacement for the Core DotNetNuke Text/HTML module. Use it where you need to repeat the form...Images Compiler: Release 0.1: Last alpha buildJavascript CallObject SOAP AJAX Helper: Beta Release, 0.2.1: Beta Release, 0.2.1 Contains only core objectskbTrainer: kbtrainer 1.25u: kbTrainer is a simple to use speed typing training HTML application. A lot of features. All ither info availiable on http://code.google.com/p/kbtr...MapWindow6: MapWindow 6.0 msi (March 16): This version fixes a bug where selected points were not drawing correctly.Mesopotamia Experiment: Mesopotamia 1.2.43: Release Notes New Features - Scenario Name on title bar - Show organisms in Scnearios with simple stats Bug Fixes - Removed app domain recyling an...MFCMAPI: March 2010 Release: If you just want to run the tool, get the executable. If you want to debug it, get the symbol file and the source. Build: 6.0.0.1018 The 64 bit bu...MVVM Light Toolkit: MVVM Light Toolkit V3: Download the Zip file and extract it to a local folder. Then, follow the instructions on the Installation page http://www.galasoft.ch/mvvm/installi...NETXPF: 1.0.2: Changes: - Added a class "IOUtils" with methods for reading streams and GZip-compressing HTTP responses - Fixed a bug in the size formatter (excep...OData SDK for Objective-C: OData SDK for Objective-C CTP: The current release supports read-only operations only and it has been tested on a limited set of scenarios. The download include a sample iPhone a...Open Data App Framework (ODAF): ODAF 1.0: Initial beta release.Selection Maker: Selection Maker 1.1: New FeaturesContext Menu for ListView added Bug FixesFixed: If the users press Copy/Cut Button when no item is selected in ListView the ListView cl...Selection Maker: Selection Maker 1.2: Bug Fixes:a minor bug fixedSimple.NET: Simple.Mocking 1.0.0.5: Initial version of a new mocking framework for .NET Revision 1: Expect.AnyInocationOn<T>(T target) changed to Expect.AnyInocationOn(object target...SQL Server Extended Properties Quick Editor: New release 1.5.4: Whats new: Move preferences to application settings and add a form to edit preferences. Support to add, modify and delete operations could be made ...SuperModel - A Dynamic View-Model Generator: 1.0.0.0 - Tyra: The final 1.0 release, now less intrusive! If you don't want to implement ISuperModel, simply implement INotifyPropertyChanged.Timecard: Timecard Initial Release: The zipped version of the Initial Checkin.Transparent Persistence.Net: TP.Net 0.1.0: This is the initial alpha release. It's working for small set of use-cases (basic access to Cassandra).VCC: Latest build, v2.1.30316.0: Automatic drop of latest buildVFPnfe: Projeto Ajuda PAF-ECF: Este projeto visa ajudar aos desenvolvedores para homologação do PAF-ECF , sob licença publica GNU/GPL para ver mais detalhes do mesmo assista o vi...Visual Studio DSite: Gif Animator: This program will make an animate gif. (Program written in Vb.Net 2008)Most Popular ProjectsMetaSharpLiveUpload to FacebookSkype Voice ChangerLiveUpload to YouTubeSIPSorceryChartPart for SharePointTFS Branching Guide 2.0TouchFlo DetacherNPandaySnippet EditorMost Active ProjectsLINQ to TwitterRawrOData SDK for PHPDirectQpatterns & practices – Enterprise LibraryBlogEngine.NETN2 CMSOpen Data App Framework (ODAF)NB_Store - Free DotNetNuke Ecommerce Catalog ModuleMapWindow6

    Read the article

  • CodePlex Daily Summary for Sunday, April 25, 2010

    CodePlex Daily Summary for Sunday, April 25, 2010New Projects281slides: 281slides is a project to demonstrate how one could go about implementing something similar to http://280slides.com in Silverlight3.Alex.XP's ARMA2 Chinese Language Pack Tools: Alex.XP's ARMA2 Chinese Language ToolsAuto Version Web Assets: The AVWA project is an HTTP Module written in C# that is designed to allow for versioning of various web assets such as .CSS and .JS files. This a...CAECE Twitter Clon: Proyecto para hacer un clon de twitter alumnos CAECE 2010DNSExchanger: Provides users to switch their PC's DNSs with pre-defined DNS with one click. Fluent ViewModel Configuration for WPF (MVVM): Fluent MVVM Configuration for WPF. A powerful yet simple interface for configuring view models for WPF. Eliminates INotifyPropertyChanged duplic...Genetic Algorithm N-Queens Solver: Genetic Algorithm N-Queens Solver with Multithreaded GUI.Hangmanondotnet: Just a starterHelium Frog Animator: Here is the Source code for the Helium Frog Animator. It is released under the GNU General Public Licence. The software enables stop motion animati...LISCH Collision Resolution, AVL Trees: LISCH Collision Resolution, AVL Trees Last Insertion Standart Colesced HashingNetPE: NetPE is a Portable Executable(PE) editor with full Metadata support. It is developed in pure C#.Proyecto Nilo: nada por ahoraSQL Schema Source Control: Track database schema changes automatically C# application that you can run against your SQL Databases (supports SQL 2008 right now, but you cou...uTorrent-Net-Client: A network client for uTorrent over the uTorrent-WebAPI. The Client use the API implementation from "uTorrent Web Client API Wrapper Library" (http:...Visual Leak Detector for Visual C++ 2008/2010: Enhanced Memory Leak Detection for Visual C++Visual Studio 2010 AutoScroller Extension: This is an extension to provide auto-scrolling to the Visual Studio 2010 environment. Simply middle click and drag the mouse in the direction yo...Vje: Vje projectVs2010-TipSite - Enter Island: This project is a visual studio 2010 project created in Silverligt. The project used to give using tips about visual studio 2010 by movies clips an...WKURM: Research Methods project @ western kentucky universityYupsky: yupsky webNew Releases.NET DiscUtils: Version 0.8: This is the 0.8 release of DiscUtils. New in this release are: An NFS client, supporting access to virtual disks held on an NFS server. A PowerS...Bluetooth Radar: Version 2.2: Add Settings window Get installed services on the deveice Check if Object Exchange is installed and changed properties. Add Windows Bluetooth...CSharp Intellisense: V1.7: major improvements: - Select best suggestion - on going changes filters (the filters will changed according to the current typing) - remember last ...DNSExchanger: DNSExchanger Beta v0.1: First release of the project, DNSExchanger. It requires, 32-bit Operating System (XP, Vista, 7) and need to be runned with administration credent...DotNetNuke® Form and List (formerly User Defined Table): 05.01.03: Form and List 05.01.03What's New: This release, Form and List 05.01.03, will be a stabilization release. It requires at least DotNetNuke 5.1.3 for...Enki Char 2 BIN: Enki Char 2 Bin: This program converts Characters to Binary and vice versaFluent ViewModel Configuration for WPF (MVVM): FluentViewModel Alpha1: This is a debug build of the FluentViewModel library. This has been provided to get feed back on the API and to look for bugs. For an example on h...Hangmanondotnet: Hangman: Just a previewHelium Frog Animator: Helium Frog 2.06 Documentation: Complete User Guide documentation in html formatHelium Frog Animator: Helium Frog 2.06 Source Code: Zip file contains all Visual Basic 6 source code, Artwork, sound files etc.Helium Frog Animator: Helium Frog Version 2.06: This file is the released version on Helium Frog 2.06. It contains binary files and required runtime libraries.Helium Frog Animator: Motion Jpeg Handling 10: Source code , module and debugging application in C# a) Module concatenates .jpg files to motion jpeg .avi file. b) Module retrieves any required ...Helium Frog Animator: Sample Grabber 03: Source code and debug program in C# a) Module lists all the available DirextX source devices b) Sets up video streaming to a picturebox by creating...Henge3D Physics Library for XNA: Henge3D Source (2010-04): The biggest change in this release was the addition of the OnCollision and OnSeparation "events" in the RigidBody class. An attached handler will r...HouseFly controls: HouseFly controls alpha 0.9.4.1: HouseFly controls release 0.9.4.1 alphaHTML Ruby: 6.22.0: Added new options for adjusting ruby line height and text line height Live preview for options Adjusted applied styles Added option to report...HTML Ruby: 6.22.1: space by word if ASCII character improved handling of unclosed ruby tagMultiwfn: Multiwfn1.3_binary: Multiwfn1.3_binaryMultiwfn: multiwfn1.3_source: multiwfn1.3_sourceRapid Dictionary: Rapid Dictionary Alpha 1.0: Try auto updatable version: http://install.rapiddict.com/index.html Rapid Dictionary Alpha 1.0 includes such functionality:you can run translation...Silverlight Input Keyboard: Version 1.5 for Silverlight 4: Dependency System.Windows.Interactivity.dll from Blend 4 RC http://www.microsoft.com/downloads/details.aspx?FamilyID=88484825-1b3c-4e8c-8b14-b05d02...SQL Schema Source Control: 1.0: Initial ReleaseUDC indexes parser: UDC indexex parser Beta: LALR(1): 1) Невозможно использовать знак распространения на общие и специальные определители, за исключением определителей в скобках (), (0), (=), ...uTorrent-Net-Client: uTorrent-Net-Client: This download contains the uTorrentNetClient and the 7Zip Windows-Service. Before you can use both, you must configuration some points in the App.C...VidCoder: 0.3.0: Changes: Added customizable columns on the Queue. Right click->Customize columns, then drag and drop to choose and reorder. Column sizes will also...Visual Leak Detector for Visual C++ 2008/2010: v2.0: New version of VLD. This adds support for x64 applications and VS 2010.Visual Studio 2010 AutoScroller Extension: AutoScroller v0.1: Initial release of Visual studio 2010 auto-scroller extension. Simply middle click and drag the mouse in the direction you wish to scroll, further...Yasbg: It's Static GUI: Many changes have been made from the previous release. Read the README! This release adds a GUI and RSS support. From now on, this program is only...Most Popular ProjectsRawrWBFS ManagerAJAX Control ToolkitSilverlight ToolkitMicrosoft SQL Server Product Samples: Databasepatterns & practices – Enterprise LibraryWindows Presentation Foundation (WPF)ASP.NETMicrosoft SQL Server Community & SamplesPHPExcelMost Active Projectspatterns & practices – Enterprise LibraryRawrGMap.NET - Great Maps for Windows Forms & PresentationBlogEngine.NETParticle Plot PivotNB_Store - Free DotNetNuke Ecommerce Catalog ModuleDotNetZip LibraryN2 CMSFarseer Physics Enginepatterns & practices: Composite WPF and Silverlight

    Read the article

  • Enum driving a Visual State change via the ViewModel

    - by Chris Skardon
    Exciting title eh? So, here’s the problem, I want to use my ViewModel to drive my Visual State, I’ve used the ‘DataStateBehavior’ before, but the trouble with it is that it only works for bool values, and the minute you jump to more than 2 Visual States, you’re kind of screwed. A quick search has shown up a couple of points of interest, first, the DataStateSwitchBehavior, which is part of the Expression Samples (on Codeplex), and also available via Pete Blois’ blog. The second interest is to use a DataTrigger with GoToStateAction (from the Silverlight forums). So, onwards… first let’s create a basic switch Visual State, so, a DataObj with one property: IsAce… public class DataObj : NotifyPropertyChanger { private bool _isAce; public bool IsAce { get { return _isAce; } set { _isAce = value; RaisePropertyChanged("IsAce"); } } } The ‘NotifyPropertyChanger’ is literally a base class with RaisePropertyChanged, implementing INotifyPropertyChanged. OK, so we then create a ViewModel: public class MainPageViewModel : NotifyPropertyChanger { private DataObj _dataObj; public MainPageViewModel() { DataObj = new DataObj {IsAce = true}; ChangeAcenessCommand = new RelayCommand(() => DataObj.IsAce = !DataObj.IsAce); } public ICommand ChangeAcenessCommand { get; private set; } public DataObj DataObj { get { return _dataObj; } set { _dataObj = value; RaisePropertyChanged("DataObj"); } } } Aaaand finally – hook it all up to the XAML, which is a very simple UI: A Rectangle, a TextBlock and a Button. The Button is hooked up to ChangeAcenessCommand, the TextBlock is bound to the ‘DataObj.IsAce’ property and the Rectangle has 2 visual states: IsAce and NotAce. To make the Rectangle change it’s visual state I’ve used a DataStateBehavior inside the Layout Root Grid: <i:Interaction.Behaviors> <ei:DataStateBehavior Binding="{Binding DataObj.IsAce}" Value="true" TrueState="IsAce" FalseState="NotAce"/> </i:Interaction.Behaviors> So now we have the button changing the ‘IsAce’ property and giving us the other visual state: Great! So – the next stage is to get that to work inside a DataTemplate… Which (thankfully) is easy money. All we do is add a ListBox to the View and an ObservableCollection to the ViewModel. Well – ok, a little bit more than that. Once we’ve got the ListBox with it’s ItemsSource property set, it’s time to add the DataTemplate itself. Again, this isn’t exactly taxing, and is purely going to be a Grid with a Textblock and a Rectangle (again, I’m nothing if not consistent). Though, to be a little jazzy I’ve swapped the rectangle to the other side (living the dream). So, all that’s left is to add some States to the template.. (Yes – you can do that), these can be the same names as the others, or indeed, something else, I have chosen to stick with the same names and take the extra confusion hit right on the nose. Once again, I add the DataStateBehavior to the root Grid element: <i:Interaction.Behaviors> <ei:DataStateBehavior Binding="{Binding IsAce}" Value="true" TrueState="IsAce" FalseState="NotAce"/> </i:Interaction.Behaviors> The key difference here is the ‘Binding’ attribute, where I’m now binding to the IsAce property directly, and boom! It’s all gravy!   So far, so good. We can use boolean values to change the visual states, and (crucially) it works in a DataTemplate, bingo! Now. Onwards to the Enum part of this (finally!). Obviously we can’t use the DataStateBehavior, it' only gives us true/false options. So, let’s give the GoToStateAction a go. Now, I warn you, things get a bit complex from here, instead of a bool with 2 values, I’m gonna max it out and bring in an Enum with 3 (count ‘em) 3 values: Red, Amber and Green (those of you with exceptionally sharp minds will be reminded of traffic lights). We’re gonna have a rectangle which also has 3 visual states – cunningly called ‘Red’, ‘Amber’ and ‘Green’. A new class called DataObj2: public class DataObj2 : NotifyPropertyChanger { private Status _statusValue; public DataObj2(Status status) { StatusValue = status; } public Status StatusValue { get { return _statusValue; } set { _statusValue = value; RaisePropertyChanged("StatusValue"); } } } Where ‘Status’ is my enum. Good times are here! Ok, so let’s get to the beefy stuff. So, we’ll start off in the same manner as the last time, we will have a single DataObj2 instance available to the Page and bind to that. Let’s add some Triggers (these are in the LayoutRoot again). <i:Interaction.Triggers> <ei:DataTrigger Binding="{Binding DataObject2.StatusValue}" Value="Amber"> <ei:GoToStateAction StateName="Amber" UseTransitions="False" /> </ei:DataTrigger> <ei:DataTrigger Binding="{Binding DataObject2.StatusValue}" Value="Green"> <ei:GoToStateAction StateName="Green" UseTransitions="False" /> </ei:DataTrigger> <ei:DataTrigger Binding="{Binding DataObject2.StatusValue}" Value="Red"> <ei:GoToStateAction StateName="Red" UseTransitions="False" /> </ei:DataTrigger> </i:Interaction.Triggers> So what we’re saying here is that when the DataObject2.StatusValue is equal to ‘Red’ then we’ll go to the ‘Red’ state. Same deal for Green and Amber (but you knew that already). Hook it all up and start teh project. Hmm. Just grey. Not what I wanted. Ok, let’s add a ‘ChangeStatusCommand’, hook that up to a button and give it a whirl: Right, so the DataTrigger isn’t picking up the data on load. On the plus side, changing the status is making the visual states change. So. We’ll cross the ‘Grey’ hurdle in a bit, what about doing the same in the DataTemplate? <Codey Codey/> Grey again, but if we press the button: (I should mention, pressing the button sets the StatusValue property on the DataObj2 being represented to the next colour). Right. Let’s look at this ‘Grey’ issue. First ‘fix’ (and I use the term ‘fix’ in a very loose way): The Dispatcher Fix This involves using the Dispatcher on the View to call something like ‘RefreshProperties’ on the ViewModel, which will in turn raise all the appropriate ‘PropertyChanged’ events on the data objects being represented. So, here goes, into turdcode-ville – population – me: First, add the ‘RefreshProperties’ method to the DataObj2: internal void RefreshProperties() { RaisePropertyChanged("StatusValue"); } (shudder) Now, add it to the hosting ViewModel: public void RefreshProperties() { DataObject2.RefreshProperties(); if (DataObjects != null && DataObjects.Count > 0) { foreach (DataObj2 dataObject in DataObjects) dataObject.RefreshProperties(); } } (double shudder) and now for the cream on the cake, adding the following line to the code behind of the View: Dispatcher.BeginInvoke(() => ((MoreVisualStatesViewModel)DataContext).RefreshProperties()); So, what does this *ahem* code give us: Awesome, it makes the single bound data object show the colour, but frankly ignores the DataTemplate items. This (by the way) is the same output you get from: Dispatcher.BeginInvoke(() => ((MoreVisualStatesViewModel)DataContext).ChangeStatusCommand.Execute(null)); So… Where does that leave me? What about adding a button to the Page to refresh the properties – maybe it’s a timer thing? Yes, that works. Right, what about using the Loaded event then eh? Loaded += (s, e) => ((MoreVisualStatesViewModel) DataContext).RefreshProperties(); Ahhh No. What about converting the DataTemplate into a UserControl? Anything is worth a shot.. Though – I still suspect I’m going to have to ‘RefreshProperties’ if I want the rectangles to update. Still. No. This DataTemplate DataTrigger binding is becoming a bit of a pain… I can’t add a ‘refresh’ button to the actual code base, it’s not exactly user friendly. I’m going to end this one now, and put some investigating into the use of the DataStateSwitchBehavior (all the ones I’ve found, well, all 2 of them are working in SL3, but not 4…)

    Read the article

  • CodePlex Daily Summary for Tuesday, July 03, 2012

    CodePlex Daily Summary for Tuesday, July 03, 2012Popular ReleasesMini SQL Query: Mini SQL Query: Just a bug fix release for when the connections try to refresh after an edit. Make sure you read the http://pksoftware.net/Content/MiniSqlQuery/Help/MiniSqlQueryQuickStart.docx for an introduction.Microsoft Ajax Minifier: Microsoft Ajax Minifier 4.58: Fix for Issue #18296: provide "ALL" value to the -ignore switch to ignore all error and warning messages. Fix for issue #18293: if encountering EOF before a function declaration or expression is properly closed, throw an appropriate error and don't crash. Adjust the variable-renaming algorithm so it's very specific when renaming variables with the same number of references so a single source file ends up with the same minified names on different platforms. add the ability to specify kno...LogExpert: 1.4 build 4566: This release for the 1.4 version line contains various fixes which have been made some times ago. Until now these fixes were only available in the 1.5 alpha versions. It also contains a fix for: 710. Column finder (press F8 to show) Terminal server issues: Multiple sessions with same user should work now Settings Export/Import available via Settings Dialog still incomple (e.g. tab colors are not saved) maybe I change the file format one day no command line support yet (for importin...DynamicToSql: DynamicToSql 1.0.0 (beta): 1.0.0 beta versionCommonLibrary.NET: CommonLibrary.NET 0.9.8.5 - Final Release: A collection of very reusable code and components in C# 4.0 ranging from ActiveRecord, Csv, Command Line Parsing, Configuration, Holiday Calendars, Logging, Authentication, and much more. FluentscriptCommonLibrary.NET 0.9.8 contains a scripting language called FluentScript. Releases notes for FluentScript located at http://fluentscript.codeplex.com/wikipage?action=Edit&title=Release%20Notes&referringTitle=Documentation Fluentscript - 0.9.8.5 - Final ReleaseApplication: FluentScript Versio...SharePoint 2010 Metro UI: SharePoint 2010 Metro UI8: Please review the documentation link for how to install. Installation takes some basic knowledge of how to upload and edit SharePoint Artifact files. Please view the discussions tab for ongoing FAQsBack-Propagation Neural Networks Simulation: Back-Propagation Neural Networks Simulation: This is the first release application for Back-Propagation Neural Networks Simulation. It is required .NET Framework 4.0. Check this to use http://backpronn.codeplex.comnopCommerce. Open source shopping cart (ASP.NET MVC): nopcommerce 2.60: Highlight features & improvements: • Significant performance optimization. • Use AJAX for adding products to the cart. • New flyout mini-shopping cart. • Auto complete suggestions for product searching. • Full-Text support. • EU cookie law support. To see the full list of fixes and changes please visit the release notes page (http://www.nopCommerce.com/releasenotes.aspx).THE NVL Maker: The NVL Maker Ver 3.51: http://download.codeplex.com/Download?ProjectName=nvlmaker&DownloadId=371510 ????:http://115.com/file/beoef05k#THE-NVL-Maker-ver3.51-sim.7z ????:http://www.mediafire.com/file/6tqdwj9jr6eb9qj/THENVLMakerver3.51tra.7z ======================================== ???? ======================================== 3.51 beta ???: ·?????????????????????? ·?????????,?????????0,?????????????????????? ·??????????????????????????? ·?????????????TJS????(EXP??) ·??4:3???,???????????????,??????????? ·?????????...????: ????2.0.3: 1、???????????。 2、????????。 3、????????????。 4、bug??,????。Generic enumeration: Enumeration.zip: Generic enumeration dll with a test console application.Apworks: Apworks (v2.5.4563.21309, 30JUN2012): Installation Prerequisites: 1. Microsoft .NET Framework 4.0 SP1 2. Microsoft Visual Studio 2010 SP1 3. Other required libraries & assemblies are now included in the installation package so no more prerequisites needed Functional Updates: 1. Refactor the identity field of the IEntity interface from 'Id' to 'ID' 2. Changed the MySql Storage to use the MySql NetConnector version 6.4.4. 3. Implemented the paging support for the repositories. 4. Added the Eager Loading Property specification t...AssaultCube Reloaded: 2.5 Intrepid: Linux has Ubuntu 11.10 32-bit precompiled binaries and Ubuntu 10.10 64-bit precompiled binaries, but you can compile your own as it also contains the source. If you are using Mac or other operating systems, download the Linux package. Try to compile it. If it fails, download a virtual machine. The server pack is ready for both Windows and Linux, but you might need to compile your own for Linux (source included) You should delete /home/config/saved.cfg to reset binds/other stuff If you us...WallSwitch: WallSwitch 1.0.4: Version 1.0.4 Changes: Changes in previous version broke hotkey support; fixed this. When minimizing the window to tray, if there are unsaved changes, then prompt to save first. When changing the path on a folder location, reset the file list. Fixed app not shutting down properly when closed externally. Improved installer to shut down app instead of requiring reboot. Clear History action now clears all history, rather than just the current theme.List Form Manipulation Framework (LFMF) for SharePoint 2010: LFMF v1.1: Added new SPFieldIO field type to reference filenamesSystem.Net.FtpClient: API Reference 2012.06.29: Updated with new file listing example as well as any API changes since the last release.Magelia WebStore Open-source Ecommerce software: Magelia WebStore 2.0: User Right Licensing ContentType version 2.0.267.1Designing Windows 8 Applications with C# and XAML: Chapters 1 - 7 Release Preview: Source code for all examples from Chapters 1 - 7 for the Release PreviewSQL Server FineBuild: Version 3.1.0: Top SQL Server FineBuild Version 3.1.0This is the stable version of FineBuild for SQL Server 2012, 2008 R2, 2008 and 2005 Documentation FineBuild Wiki containing details of the FineBuild process Known Issues Limitations with this release FineBuild V3.1.0 Release Contents List of changes included in this release Please DonateFineBuild is free, but please donate what you think FineBuild is worth as everything goes to charity. Tearfund is one of the UK's leading relief and de...EasySL: RapidSL V2: Rewrite RapidSL UI Framework, Using Silverlight 5.0 EF4.1 Code First Ria Service SP2 + Lastest Silverlight Toolkit.New Projects2DoTasks: This is a simple Dnn Module for Project/Tasks/time management. I hope you all found it useful.AOPify: AOPify lightweight fluent AOP framework that provides basic AOP features both before,after,onerror etc with fluent syntax..Capacitacion: This is my first Project - mvillasecoCLFiling: Client filing with search functionsContoso University MVC NTier: This is first version reference application for ASP.NET MVC NTier.DynamicToSql: DynamicToSql is a lightweight API that maps dynamically typed entities to a database and vice versa. It works against any database that has ADO.NET drivers.Enlightener: Deobfuscator target at Confuser. Child project of http://netdeob0.codeplex.com/Excel Adjacency List to Dot: Excel add-in to generate graphs in GraphViz dot file format from an adjacency list in Excel.FFXIV Job Bar: This is a little utility to help with Job changes in FFXIV. Gallery: A simple javascript/jquery based image gallery. Just include the Gallery.js and jquery in your html page.Grocery Droid: Transfer your P.C. designed shopping list to androidLOCOL: Locol is a internet medium to provide local information and services to district local residents.Meter: Log communal meters dataNthDownload: NthDownload is yet another attempt at a download manager.Paginacion de un objeto en un gridview: Como paginar un objeto con multiples resultados en un gridviewRunman game: "Runman" is port of "Pac-Man" game writing on C# and XNASB01: Project will be a startup for a warehouse management and easy to extend by any developer. Plug n play kind of setup.SC2Ranks API: A .NET 4.0 SC2Ranks APISharePoint 2010 Cookie Approval Control: If you need to comply with EU cookie law this control displays a message to each user that cookies are in use on the site and allows them to accept the messageSharePoint Advanced Visibility Options: Advanced Visibility Options - is an extension to SharePoint providing configurable List Field Iterator with PowerShell scripts.smtools2: Add-on tools for Service MonsterSparqube Picture Column Lite for SharePoint 2010: Sparqube Picture Column Lite is simple component for uploading and displaying images in SharePoint 2010 lists.SpudloFizzBuzz: This project is part of a job application process.SwiftMVVM: An extremely fast, easily refactorable implementation of INotifyPropertyChanged/ing, using dynamic proxy generation, as well as a robust change tracking engine.ZPL Converter: ZPL Converter converts Zune Playlists (.ZPL) easily and fast into other playlist formats, e.g. '.M3U' or '.PLS'.

    Read the article

  • CodePlex Daily Summary for Wednesday, December 19, 2012

    CodePlex Daily Summary for Wednesday, December 19, 2012Popular ReleasesToolbox for Dynamics CRM 2011: XrmToolBox (1.0.0.0): Initial Release Contains following tools: Attribute Bulk Updater Iconator Role Updater Scripts Finder SiteMap Editor Solution Import View Layout Replicator WebResources Manager Also include the sample tool described in the documentation "How to develop your own tool" More tools to come later...NB_Store - Free DotNetNuke Ecommerce Catalog Module: NB_Store v2.3.3 Rel0: DNN 5.3.2 and above, and DNN 6 Compatible - Some release notes are discussed here. Important : v2.3.3 requires the Back Office module to be placed onto a seperate page to the productlist. During the upgrade process, this module retains your existing configuration by not overwriting any existing settings and templates. If you wish to reset your configuration to gain all new settings and templates, please review this KB article. Please view the following documentation if you are installing ...F# PowerPack with F# Compiler Source Drops: PowerPack for FSharp 3.0 + .NET 4.x + VS2010: This is a release of the old FSharp Power Pack binaries recompiled for F# 3.0, .NET 4.0/4.5 and Silveright 5. NOTE: This is for F# 3.0 & .NET 4.0 or F# 3.0 & Silverlight 5 NOTE: The assemblies are no longer strong named NOTE: The assemblies are not added to the GAC NOTE: In some cases functionality overlaps with F# 3.0, e.g. SI Units of measurecodeSHOW: codeSHOW AppPackage Release 16: This release is a package file built out of Visual Studio that you can side load onto your machine if for some reason you don't have access to the Windows Store. To install it, just unzip and run the .ps1 file using PowerShell (right click | run with PowerShell). Attention: if you want to download the source code for codeSHOW, you're in the wrong place. You need to go to the SOURCE CODE tab.Move Mouse: Move Mouse 2.5.3: FIXED - Issue where it errors on load if the screen saver interval is over 333 minutes.LINUX????????: LINUX????????: LINUX????????cnbeta: cnbeta: cnbetaCSDN ??: CSDN??????: CSDN??????PowerShell Community Extensions: 2.1.1 Production: PowerShell Community Extensions 2.1.1 Release NotesDec 16, 2012 This version of PSCX supports both Windows PowerShell 2.0 and 3.0. Bug fix for HelpUri error with the Get-Help proxy command. See the ReleaseNotes.txt download above for more information.VidCoder: 1.4.11 Beta: Added Hungarian translation, thanks to Brechler Zsolt. Update HandBrake core to SVN 5098. This update should fix crashes on some files. Updated the enqueue split button to fit in better with the active Windows theme. Updated presets to use x264 preset/profile/level.???: Cnblogs: CNBLOGSSandcastle Help File Builder: SHFB v1.9.6.0 with Visual Studio Package: General InformationIMPORTANT: On some systems, the content of the ZIP file is blocked and the installer may fail to run. Before extracting it, right click on the ZIP file, select Properties, and click on the Unblock button if it is present in the lower right corner of the General tab in the properties dialog. This new release contains bug fixes and feature enhancements. There are some potential breaking changes in this release as some features of the Help File Builder have been moved into...Electricity, Gas and Temperature Monitoring with Netduino Plus: V1.0.1 Netduino Plus Monitoring: This is the first stable release from the Netduino Plus Monitoring program. Bugfixing The code is enhanced at some places in respect to the V0.6.1 version There is a possibility to add multiple S0 meters Website for realtime display of data Website for configuring the Netduino Comments are welcome! Additions will not be made to this version. This is the first and last major Netduino Plus V1 release. The new development will take place with the Netduino Plus V2 development board in mi...Windows Store Application Library: Windows Store Application Library - 1.1.1.0: Windows Store Application Library StoreAppLib can be installed from Visual Studio "Manage NuGet Packages" tool. This release of Windows Store Application Library contains following controls and utilities. DatePicker control TimePicker control PageHeaderTextBlock control with Global Navigation Menu Popup manager AppBarButton control TapEffect animation DateTimeConverter ConcatenationConverter CountConverterCRM 2011 Visual Ribbon Editor: Visual Ribbon Editor (1.3.1116.8): [FIX] Fixed issue not displaying CRM system button images correctly (incorrect path in file VisualRibbonEditor.exe.config)My Expenses Windows Store LOB App Demo: My Expenses Version 1: This is version 1 of the MyExpenses Windows 8 line of business demo app. The app is written in XAML and C#. It calls a WCF service that works with a SQL Server database. The app uses the Callisto toolkit. You can get it at https://github.com/timheuer/callisto. The Expenses.sql file contains the SQL to create the Expenses database. The ExpensesWCFService.zip file contains the WCF service, also written in C#. You should create a WCF service. Create an Entity Framework model and point it to...Manage upload files for SP 2010: Manage upload files (SP 2010) 1.0.0: Version 1.0.0: Manage upload file size on specific application page Simple in use Simple installation Work on: SharePoint Foundation 2010 Sharepoint Server 2010 (Standard, Enterprise) Localized: English RussianMCEBuddy Viewer: MCEBuddy Viewer 1.0.0 Beta: MCEBuddy Viewer for MCEBuddy 2.x Windows Media Center Add-On to view the current job status of MCEbuddy. Requirements: 1. Installed MCEBuddy 2.x (tested on release 2.3.7-2.3.10) http://mcebuddy2x.codeplex.com 2. Windows Media Center (tested on Windows 7 Pro 32-bit&64-bit, Windows 8 Pro with WMC 64-bit) Before installing the new version of Plug-in uninstall old version through windows control panelBlackJumboDog: Ver5.7.4: 2012.12.13 Ver5.7.4 (1)Web???????、???????????????????????????????????????????VFPX: ssClasses A1.0: My initial release. See https://vfpx.codeplex.com/wikipage?title=ssClasses&referringTitle=Home for a brief description of what is inside this releaseNew ProjectsAutonomic Middleware: Reflective middleware using workflow that makes the middleware autonomic.Battleforge: Assault: A card battle game. This project is being built using Silverlight 4 in C#.ChurajPatterns: Design patterns testing and overview console application.FimExplorer: Tool for executing XPath queries against FIM without going through it's web portal.Financial Management Studio: This is a WPF application for the financial management. Will use bunch of technologies such as: MVVM, Microsoft Extension Framework and Entities Framework.iJob: Do u no what is this?Developed with C#.net3.5 MSSQL2008Interaction Production Server: A software based networked lighting controller. It brokers many protocols together to allow easy setup and development of new stage lighting controllers.Interface weaver Custom Tool: A CustomTool for vs auto implementing interface based on aspects (auto INotifyPropertychanged data context implementation, auto command mapping...).IntroductionWeb: This is the second time for us to build something extraordinaryiSteam: iSteam is a product being developed focusing on the Steamworks platform, to advertise and centralize everything about steam in one application.iSun_PLS: iSun PLS is a Photo libary System, to help you manager your pictures on your server!LSharp: A Scripting Language Interpreter for .NETMassive Dangerzone: Don't try this at home.MinGuid: An alternative / replacement for those long Guid strings, simply call the function in the library which generates the Unique 16 character string.Nx Portable Framework: Framework aiming to speed up cross platform movile developement.Orchard Training Demo module: Demo Orchard module for training purposes. This module completes the training materials at http://english.orchardproject.hu/Training/Oriol ASAP: ASAPPanopticonize API: This project provides code samples for the panopticonize.com video thumbnailing API.Registry Editor Navigator: The small utility that takes a path and makes Regedit open to that path. Similar to RegJump but it has UI, uses clipboard and has a global keyboard hook. SafetyExam: ??????????????Simple Queuing System: This project is created to show you how queuing system can be implemented in MSMQ in C#. The sample is implemented from real life queuing system. TypeScript plugin enhancements for VS 2010 add-in: This add-in allows to - Compile .ts files by saveVisual Studio Help Downloader 2012: Tool for downloading the Visual Studio 2012 help packages for offline useWebGoat.NET test repository: THis is a clone of the WebGoat.NET project hosted at GitHub, provided here for those who need to be able to have a TFS-accessible copy of WebGoat.WebPythonHost: A .NET application hosting web python environment.Wpf Sqlite Management: about 1 month i publish this project and use avalon edit and avalon doc in my project WPFSchematics: The WPFSchematics is a vector graphic interactive system,and based on WPF graphics technology.XEasyFileSearch: easy and quick file searcherZweiBooks: Plugin for a Bukkit-Server.

    Read the article

  • CodePlex Daily Summary for Thursday, May 31, 2012

    CodePlex Daily Summary for Thursday, May 31, 2012Popular ReleasesNaked Objects: Naked Objects Release 4.1.0: Corresponds to the packaged version 4.1.0 available via NuGet. Note that the versioning has moved to SemVer (http://semver.org/) This is a bug fix release with no new functionality. Please note that the easiest way to install and run the Naked Objects Framework is via the NuGet package manager: just search the Official NuGet Package Source for 'nakedobjects'. It is only necessary to download the source code (from here) if you wish to modify or re-build the framework yourself. If you do wi...Microsoft Ajax Minifier: Microsoft Ajax Minifier 4.54: Fix for issue #18161: pretty-printing CSS @media rule throws an exception due to mismatched Indent/Unindent pair.OMS.Ice - T4 Text Template Generator: OMS.Ice - T4 Text Template Generator v1.4.0.14110: Issue 601 - Template file name cannot contain characters that are not allowed in C#/VB identifiers Issue 625 - Last line will be ignored by the parser Issue 626 - Usage of environment variables and macrosSilverlight Toolkit: Silverlight 5 Toolkit Source - May 2012: Source code for December 2011 Silverlight 5 Toolkit release.totalem: version 2012.05.30.1: Beta version added function for mass renaming files and foldersAudio Pitch & Shift: Audio Pitch and Shift 4.4.0: Tracklist added on main window Improved performances with tracklist Some other fixesJson.NET: Json.NET 4.5 Release 6: New feature - Added IgnoreDataMemberAttribute support New feature - Added GetResolvedPropertyName to DefaultContractResolver New feature - Added CheckAdditionalContent to JsonSerializer Change - Metro build now always uses late bound reflection Change - JsonTextReader no longer returns no content after consecutive underlying content read failures Fix - Fixed bad JSON in an array with error handling creating an infinite loop Fix - Fixed deserializing objects with a non-default cons...Indent Guides for Visual Studio: Indent Guides v12.1: Version History Changed in v12.1: Fixed crash when unable to start asynchronous analysis Fixed upgrade from v11 Changed in v12: background document analysis new options dialog with Quick Set selections for behavior new "glow" style for guides new menu icon in VS 11 preview control now uses editor theming highlighting can be customised on each line fixed issues with collapsed code blocks improved behaviour around left-aligned pragma/preprocessor commands (C#/C++) new setting...DotNetNuke® Community Edition CMS: 06.02.00: Major Highlights Fixed issue in the Site Settings when single quotes were being treated as escape characters Fixed issue loading the Mobile Premium Data after upgrading from CE to PE Fixed errors logged when updating folder provider settings Fixed the order of the mobile device capabilities in the Site Redirection Management UI The User Profile page was completely rebuilt. We needed User Profiles to have multiple child pages. This would allow for the most flexibility by still f...Thales Simulator Library: Version 0.9.6: The Thales Simulator Library is an implementation of a software emulation of the Thales (formerly Zaxus & Racal) Hardware Security Module cryptographic device. This release fixes a problem with the FK command and a bug in the implementation of PIN block 05 format deconstruction. A new 0.9.6.Binaries file has been posted. This includes executable programs without an installer, including the GUI and console simulators, the key manager and the PVV clashing demo. Please note that you will need ...????: ????2.0.1: 1、?????。WiX Toolset: WiX v3.6 RC: WiX v3.6 RC (3.6.2928.0) provides feature complete Burn with VS11 support. For more information see Rob's blog post about the release: http://robmensching.com/blog/posts/2012/5/28/WiX-v3.6-Release-Candidate-availableJavascript .NET: Javascript .NET v0.7: SetParameter() reverts to its old behaviour of allowing JavaScript code to add new properties to wrapped C# objects. The behavior added briefly in 0.6 (throws an exception) can be had via the new SetParameterOptions.RejectUnknownProperties. TerminateExecution now uses its isolate to terminate the correct context automatically. Added support for converting all C# integral types, decimal and enums to JavaScript numbers. (Previously only the common types were handled properly.) Bug fixe...callisto: callisto 2.0.29: Added DNS functionality to scripting. See documentation section for details of how to incorporate this into your scripts.Phalanger - The PHP Language Compiler for the .NET Framework: 3.0 (May 2012): Fixes: unserialize() of negative float numbers fix pcre possesive quantifiers and character class containing ()[] array deserilization when the array contains a reference to ISerializable parsing lambda function fix round() reimplemented as it is in PHP to avoid .NET rounding errors filesize bypass for FileInfo.Length bug in Mono New features: Time zones reimplemented, uses Windows/Linux databaseSharePoint Euro 2012 - UEFA European Football Predictor: havivi.euro2012.wsp (1.1): New fetures:Admin enable / disable match Hide/Show Euro 2012 SharePoint lists (3 lists) Installing SharePoint Euro 2012 PredictorSharePoint Euro 2012 Predictor has been developed as a SharePoint Sandbox solution to support SharePoint Online (Office 365) Download the solution havivi.euro2012.wsp from the download page: Downloads Upload this solution to your Site Collection via the solutions area. Click on Activate to make the web parts in the solution available for use in the Site C...ScreenShot: InstallScreenShot: This is the current stable release.????SDK for .Net 4.0+(OAuth2.0+??V2?API): ??V2?SDK???: ?????????API?? ???????OAuth2.0?? ????:????????????,??????????“SOURCE CODE”?????????Changeset,http://weibosdk.codeplex.com/SourceControl/list/changesets ???:????????,DEMO??AppKey????????????????,?????AppKey,????AppKey???????????,?????“????>????>????>??????”.Net Code Samples: Code Samples: Code samples (SLNs).LINQ_Koans: LinqKoans v.02: Cleaned up a bitNew ProjectsAAABBBCCC: hauhuhaAutomação e Robótica: Sistema de automação e robótica de periféricos. todo o projeto consiste em integrar interface de controle pelo software do hardware para realização de comando e acionamentos eletricos e eletromecânicos.Barium Live! API Client: Simple test client for the Barium Live! REST API Contact Barium Live! support on http://www.bariumlive.com/support to get an API key for development. Please note that the test client has a dependency to the Newtonsoft Json.NET library that has to be downloaded separately from http://json.codeplex.com/BizTalk Host Restarter: This is a quick tool that I wrote to more quickly Stop, Start and Restart the BizTalk Host instances. It's command line, with full source code, I use it in my build scripts and deploy scripts, works a treat. MUCH faster than the BizTalk Admin Console can do the same task. CNAF Portal: CNAFPortalConsulta_Productos: Nos permite ingresar un código del 1 al 10..... y al dar clic en buscar nos aparecerá un mensaje con el nombre del producto de dicho código.Deployment Tool: Deployement is a small piece in our IT lifecycle for many small projects. But, considering that you are working for a large project, it has many servers, softwares, configurations, databases and so on. The problem emits, even you have upgrades and version controls. The deploymentool is a solution which can help you resolve the difficulties described above.Devmil MVVM: A toolset for MVVM development with focus on INotifyPropertyChanged and dependenciesEAL: no summaryEasyCLI: EasyCLI is a command shell for the Commodore 64 computer. EasyCLI is packaged as an EasyFlash cartridge.ExcelSharePointListSync: This tool help is Getting Data Form SharePoint to Excel 2010 , Following are the silent feature : 1) Maintain a List connection Offline 2) Choose to get data Form a View of Form Columns 3) Sync the data Back to SharePoint GH: Some summaryicontrolpcv: icontrolpvcLotteryVoteMVC: LotteryVote use mvcMail API for Windows Phone 7: Library that allows developers to add some email functionality to their application, like sending and reading email messages, with the capability of adding attachments to the messages. Matchy - Fashion Website: Fashion website for Match Brand, a fashion brand of BOOM JSC.,MIracLE Guild Admin System: asdOrchard Content Picker: Orchard Content Picker enables content editor to select Content Items.ProSoft Mail Services: This project implements a mail server that allows sending mail with SMTP and access the mailbox via POP. Later on, the server also get a MAPI interface and an interface for SPAM defense.Silver Sugar Web Browser: This is a simple web browser named "Silver Sugar". It has a back button, forward button, home button, url text box and a go button.social sdk for windows phone: Windows Phone Social Share Lib. (Including Weibo, Tencent Weibo & Renren)SolutionX: dfsdf asdfds asdfsdf asdfsdfspUtils: This project aims to facilitate easy to use methods that interact with SharePoint's Client OM/JSOM.Streambolics Library: A library of C# classes providing robust tools for real-time data monitoringTestExpression: TestExpressionTFS Helper package: VS2010 is well integrated to TFS and has all the features required on day to day basis. Most common feature any developer use is managing workitems. Creating work items is very easy as is copying work items, but what I need is to copy workitem between projects retaining links and attachments. I am sure this is not Ideal and against sprint projects.Ubelsoft: Sistema de Registro Eletrônico de Ponto - SREPZombieSim: Simulate the spread of a zombie virusZYWater: ......................

    Read the article

  • Adventures in Windows 8: Placing items in a GridView with a ColumnSpan or RowSpan

    - by Laurent Bugnion
    Currently working on a Windows 8 app for an important client, I will be writing about small issues, tips and tricks, ideas and whatever occurs to me during the development and the integration of this app. When working with a GridView, it is quite common to use a VariableSizedWrapGrid as the ItemsPanel. This creates a nice flowing layout which will auto-adapt for various resolutions. This is ideal when you want to build views like the Windows 8 start menu. However immediately we notice that the Start menu allows to place items on one column (Smaller) or two columns (Larger). This switch happens through the AppBar. So how do we implement that in our app? Using ColumnSpan and RowSpan When you use a VariableSizedWrapGrid directly in your XAML, you can attach the VariableSizedWrapGrid.ColumnSpan and VariableSizedWrapGrid.RowSpan attached properties directly to an item to create the desired effect. For instance this code create this output (shown in Blend but it runs just the same): <VariableSizedWrapGrid ItemHeight="100" ItemWidth="100" Width="200" Orientation="Horizontal"> <Rectangle Fill="Purple" /> <Rectangle Fill="Orange" /> <Rectangle Fill="Yellow" VariableSizedWrapGrid.ColumnSpan="2" /> <Rectangle Fill="Red" VariableSizedWrapGrid.ColumnSpan="2" VariableSizedWrapGrid.RowSpan="2" /> <Rectangle Fill="Green" VariableSizedWrapGrid.RowSpan="2" /> <Rectangle Fill="Blue" /> <Rectangle Fill="LightGray" /> </VariableSizedWrapGrid> Using the VariableSizedWrapGrid as ItemsPanel When you use a GridView however, you typically bind the ItemsSource property to a collection, for example in a viewmodel. In that case, you want to be able to switch the ColumnSpan and RowSpan depending on properties on the item. I tried to find a way to bind the VariableSizedWrapGrid.ColumnSpan attached property on the GridView’s ItemContainerStyle template to an observable property on the item, but it didn’t work. Instead, I decided to use a StyleSelector to switch the GridViewItem’s style. Here’s how: First I added my two GridViews to my XAML as follows: <Page.Resources> <local:MainViewModel x:Key="Main" /> <DataTemplate x:Key="DataTemplate1"> <Grid Background="{Binding Brush}"> <TextBlock Text="{Binding BrushCode}" /> </Grid> </DataTemplate> </Page.Resources> <Page.DataContext> <Binding Source="{StaticResource Main}" /> </Page.DataContext> <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Margin="20"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <GridView ItemsSource="{Binding Items}" ItemTemplate="{StaticResource DataTemplate1}" VerticalAlignment="Top"> <GridView.ItemsPanel> <ItemsPanelTemplate> <VariableSizedWrapGrid ItemHeight="150" ItemWidth="150" /> </ItemsPanelTemplate> </GridView.ItemsPanel> </GridView> <GridView Grid.Column="1" ItemsSource="{Binding Items}" ItemTemplate="{StaticResource DataTemplate1}" VerticalAlignment="Top"> <GridView.ItemsPanel> <ItemsPanelTemplate> <VariableSizedWrapGrid ItemHeight="100" ItemWidth="100" /> </ItemsPanelTemplate> </GridView.ItemsPanel> </GridView> </Grid> The MainViewModel looks like this: public class MainViewModel { public IList<Item> Items { get; private set; } public MainViewModel() { Items = new List<Item> { new Item { Brush = new SolidColorBrush(Colors.Red) }, new Item { Brush = new SolidColorBrush(Colors.Blue) }, new Item { Brush = new SolidColorBrush(Colors.Green), }, // And more... }; } } As for the Item class, I am using an MVVM Light ObservableObject but you can use your own simple implementation of INotifyPropertyChanged of course: public class Item : ObservableObject { public const string ColSpanPropertyName = "ColSpan"; private int _colSpan = 1; public int ColSpan { get { return _colSpan; } set { Set(ColSpanPropertyName, ref _colSpan, value); } } public SolidColorBrush Brush { get; set; } public string BrushCode { get { return Brush.Color.ToString(); } } } Then I copied the GridViewItem’s style locally. To do this, I use Expression Blend’s functionality. It has the disadvantage to copy a large portion of XAML to your application, but the HUGE advantage to allow you to change the look and feel of your GridViewItem everywhere in the application. For example, you can change the selection chrome, the item’s alignments and many other properties. Actually everytime I use a ListBox, ListView or any other data control, I typically copy the item style to a resource dictionary in my application and I tweak it. Note that Blend for Windows 8 apps is automatically installed with every edition of Visual Studio 2012 (including Express) so you have no excuses anymore not to use Blend :) Open MainPage.xaml in Expression Blend by right clicking on the MainPage.xaml file in the Solution Explorer and selecting Open in Blend from the context menu. Note that the items do not look very nice! The reason is that the default ItemContainerStyle sets the content’s alignment to “Center” which I never quite understood. Seems to me that you rather want the content to be stretched, but anyway it is easy to change.   Right click on the GridView on the left and select Edit Additional Templates, Edit Generated Item Container (ItemContainerStyle), Edit a Copy. In the Create Style Resource dialog, enter the name “DefaultGridViewItemStyle”, select “Application” and press OK. Side note 1: You need to save in a global resource dictionary because later we will need to retrieve that Style from a global location. Side note 2": I would rather copy the style to an external resource dictionary that I link into the App.xaml file, but I want to keep things simple here. Blend switches in Template edit mode. The template you are editing now is inside the ItemContainerStyle and will govern the appearance of your items. This is where, for instance, the “checked” chrome is defined, and where you can alter it if you need to. Note that you can reuse this style for all your GridViews even if you use a different DataTemplate for your items. Makes sense? I probably need to think about writing another blog post dedicated to the ItemContainerStyle :) In the breadcrumb bar on top of the page, click on the style icon. The property we want to change now can be changed in the Style instead of the Template, which is a better idea. Blend is not in Style edit mode, as you can see in the Objects and Timeline pane. In the Properties pane, in the Search box, enter the word “content”. This will filter all the properties containing that partial string, including the two we are interested in: HorizontalContentAlignment and VerticalContentAlignment. Set these two values to “Stretch” instead of the default “Center”. Using the breadcrumb bar again, set the scope back to the Page (by clicking on the first crumb on the left). Notice how the items are now showing as squares in the first GridView. We will now use the same ItemContainerStyle for the second GridView. To do this, right click on the second GridView and select Edit Additional Templates, Edit Generate Item Container, Apply Resource, DefaultGridViewItemStyle. The page now looks nicer: And now for the ColumnSpan! So now, let’s change the ColumnSpan property. First, let’s define a new Style that inherits the ItemContainerStyle we created before. Make sure that you save everything in Blend by pressing Ctrl-Shift-S. Open App.xaml in Visual Studio. Below the newly created DefaultGridViewItemStyle resource, add the following style: <Style x:Key="WideGridViewItemStyle" TargetType="GridViewItem" BasedOn="{StaticResource DefaultGridViewItemStyle}"> <Setter Property="VariableSizedWrapGrid.ColumnSpan" Value="2" /> </Style> Add a new class to the project, and name it MainItemStyleSelector. Implement the class as follows: public class MainItemStyleSelector : StyleSelector { protected override Style SelectStyleCore(object item, DependencyObject container) { var i = (Item)item; if (i.ColSpan == 2) { return Application.Current.Resources["WideGridViewItemStyle"] as Style; } return Application.Current.Resources["DefaultGridViewItemStyle"] as Style; } } In MainPage.xaml, add a resource to the Page.Resources section: <local:MainItemStyleSelector x:Key="MainItemStyleSelector" /> In MainPage.xaml, replace the ItemContainerStyle property on the first GridView with the ItemContainerStyleSelector property, pointing to the StaticResource we just defined. <GridView ItemsSource="{Binding Items}" ItemTemplate="{StaticResource DataTemplate1}" VerticalAlignment="Top" ItemContainerStyleSelector="{StaticResource MainItemStyleSelector}"> <GridView.ItemsPanel> <ItemsPanelTemplate> <VariableSizedWrapGrid ItemHeight="150" ItemWidth="150" /> </ItemsPanelTemplate> </GridView.ItemsPanel> </GridView> Do the same for the second GridView as well. Finally, in the MainViewModel, change the ColumnSpan property on the 3rd Item to 2. new Item { Brush = new SolidColorBrush(Colors.Green), ColSpan = 2 }, Running the application now creates the following image, which is what we wanted. Notice how the green item is now a “wide tile”. You can also experiment by creating different Styles, all inheriting the DefaultGridViewItemStyle and using different values of RowSpan for instance. This will allow you to create any layout you want, while leaving the heavy lifting of “flowing the layout” to the GridView control. What about changing these values dynamically? Of course as we can see in the Start menu, it would be nice to be able to change the ColumnSpan and maybe even the RowSpan values at runtime. Unfortunately at this time I have not found a good way to do that. I am investigating however and will make sure to post a follow up when I find what I am looking for!   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • CodePlex Daily Summary for Sunday, June 17, 2012

    CodePlex Daily Summary for Sunday, June 17, 2012Popular ReleasesXDA ROM Hub: XDA ROM Hub v0.35 Beta: Download and install stock ROM -- Not all ROMS are online. Flash CWM On locked bootloader. Root. Unroot. Flash kernels. Flash system image Erase system. Erase boot. Erase Data and Cache. Install update.zip. Install ROM addons. Install Boot animations. Unlock bootloader. Please rate and reviewCodename 'Chrometro': Developer Preview: Welcome to the Codename 'Chrometro' Developer Preview! This is the very first public preview of the app. Please note that this is a highly primitive build and the app is not even half of what it is meant to be. The Developer Preview sports the following: 1) An easy to use application setup. 2) The Assistant which simplifies your task of customization. 3) The partially complete Metro UI. 4) A variety of settings 5) A partially complete web browsing experience To get started, download the Ins...Cosmos (C# Open Source Managed Operating System): Release 92560: Prerequisites Visual Studio 2010 - Any version including Express. Express users must also install Visual Studio 2010 Integrated Shell runtime VMWare - Cosmos can run on real hardware as well as other virtualization environments but our default debug setup is configured for VMWare. VMWare Player (Free). or Workstation VMWare VIX API 1.11AutoUpdaterdotNET : Autoupdate for VB.NET and C# Developer: AutoUpdater.NET 1.1: Release Notes *New feature added that allows user to select remind later interval.Sumzlib: API document: API documentMicrosoft SQL Server Product Samples: Database: AdventureWorks 2008 OLTP Script: Install AdventureWorks2008 OLTP database from script The AdventureWorks database can be created by running the instawdb.sql DDL script contained in the AdventureWorks 2008 OLTP Script.zip file. The instawdb.sql script depends on two path environment variables: SqlSamplesDatabasePath and SqlSamplesSourceDataPath. The SqlSamplesDatabasePath environment variable is set to the default Microsoft ® SQL Server 2008 path. You will need to change the SqlSamplesSourceDataPath environment variable to th...HigLabo: HigLabo_20120613: Bug fix HigLabo.Mail Decode header encoded by CP1252Jasc (just another script compressor): 1.3.1: Updated Ajax Minifier to 4.55.WipeTouch, a jQuery touch plugin: 1.2.0: Changes since 1.1.0: New: wipeMove event, triggered while moving the mouse/finger. New: added "source" to the result object. Bug fix: sometimes vertical wipe events would not trigger correctly. Bug fix: improved tapToClick handler. General code refactoring. Windows Phone 7 is not supported, yet! Its behaviour is completely broken and would require some special tricks to make it work. Maybe in the future...Phalanger - The PHP Language Compiler for the .NET Framework: 3.0.0.3026 (June 2012): Fixes: round( 0.0 ) local TimeZone name TimeZone search compiling multi-script-assemblies PhpString serialization DocDocument::loadHTMLFile() token_get_all() parse_url()BlackJumboDog: Ver5.6.4: 2012.06.13 Ver5.6.4  (1) Web???????、???POST??????????????????CRM 2011 ERD Designer: CRM 2011 ERD Designer: CRM 2011 ERD Designer BETA version is now availableBumblebee: Version 0.3.1: Changed default config values to decent ones. Restricted visibility of Hive.fs to internal. Added some XML documentation. Added Array.shuffle utility. The dll is also available on NuGet My apologies, the initial source code referenced was missing one file which prevented it from building The source code contains two examples, one in C#, one in F#, illustrating the usage of the framework on the Travelling Salesman Problem: Source CodeSharePoint XSL Templates: SPXSLT 0.0.9: Added new template FixAmpersands. Fixed the contents of the MultiSelectValueCheck.xsl file, which was missing the stylesheet wrapper.ExcelFileEditor: .CS File: nothingWeapsy - ASP.NET MVC CMS: 1.0.0 RC: - Upgrade to Entity Framework 4.3.1 - Added AutoMapper custom version (by nopCommerce Team) - Added missed model properties and localization resources of Plugin Definitions - Minor changes - Fixed some bugsXenta Framework - extensible enterprise n-tier application framework: Xenta Framework 1.8.0 Beta: Catalog and Publication reviews and ratings Store language packs in data base Improve reporting system Improve Import/Export system A lot of WebAdmin app UI improvements Initial implementation of the WebForum app DB indexes Improve and simplify architecture Less abstractions Modernize architecture Improve, simplify and unify API Simplify and improve testing A lot of new unit tests Codebase refactoring and ReSharpering Utilize Castle Windsor Utilize NHibernate ORM ...Microsoft Ajax Minifier: Microsoft Ajax Minifier 4.55: Properly handle IE extension to CSS3 grammar that allows for multiple parameters to functional pseudo-class selectors. add new switch -braces:(new|same) that affects where opening braces are placed in multi-line output. The default, "new" puts them on their own new line; "same" outputs them at the end of the previous line. add new optional values to the -inline switch: -inline:(force|noforce), which can be combined with the existing boolean value via comma-separators; value "force" (which...Microsoft Media Platform: Player Framework: MMP Player Framework 2.7 (Silverlight and WP7): Additional DownloadsSMFv2.7 Full Installer (MSI) - This will install everything you need in order to develop your own SMF player application, including the IIS Smooth Streaming Client. It only includes the assemblies. If you want the source code please follow the link above. Smooth Streaming Sample Player - This is a pre-built player that includes support for IIS Smooth Streaming. You can configure the player to playback your content by simplying editing a configuration file - no need to co...Liberty: v3.2.1.0 Release 10th June 2012: Change Log -Added -Liberty is now digitally signed! If the certificate on Liberty.exe is missing, invalid, or does not state that it was developed by "Xbox Chaos, Open Source Developer," your copy of Liberty may have been altered in some (possibly malicious) way. -Reach Mass biped max health and shield changer -Fixed -H3/ODST Fixed all of the glitches that users kept reporting (also reverted the changes made in 3.2.0.2) -Reach Made some tag names clearer and more consistent between m...New ProjectsAir Sanity: its a Project for a Microsoft ContestAsp.Net Settings Checking: Simple page for review all settings for web application ASP.Net 2.0. Ex: email setting, MS SQL setting,...ATH Commander: Projekt tworzony na zaliczenie przedmiotuCold Flame Youtube Library: .net library to download youtube videos, get youtube video titles and rip audio from a youtube videoComponentModelEx: This project add functionalities to handle the INotifyPropertyChanged interface. It also includes a bit of the MVVM pattern.CRUD Services: Provides a single generic CRUD service that can handle CRUD operations for any entity. Includes wrappers for supporting backend frameworks like Entity Framework and Linq-To-Sql, as well as for communication stacks like WCF and ASP.NET Web API.DotNetNuke Persian Packages: ???? ????? ? ???? ??? ?? ???? ???? 6.1.5 ???? ????? ??? ?? ???? - ??? ?? ?? ??FactureManger: With Facture manager you can easily create products, users, business partners and add them into Factures. This application can help to any business. GetSP2010ListIDs: This application is most useful while performing a manual deployment or backup/restore of SP2010 sites/lists/libraries from one environment to anotherKTOP Homeworks: ???????? ??????? ?? ?????Minecraft Italian Utility: Applicazione originariamente pubblicata su minecraftitalia.net, qui ci saranno le release e gli aggiornamenti My_first_Codeplex_project: My first Codeplex projectOAuth .NET Client: This project implements an OAuth client library in C# .NET.Painter: Hello! This is the help file for the Painter program. With this file you will be introduced into the futures of the program and the secrets of the program. PDN C++ AMP Effects: Paint.NET Gaussian blur effect written in C++ AMPThe East Wedding: This is a website for the East WeddingXDesigner.Writer: .XDesigner.Writer is a Document Editor like MS Word , Written in 100% C# code , without any the 3th part component , without RTF Text box , MS Word component or

    Read the article

  • Q1 2010 New Feature: Paging with RadGridView for Silverlight and WPF

    We are glad to announce that the Q1 2010 Release has added another weapon to RadGridViews growing arsenal of features. This is the brand new RadDataPager control which provides the user interface for paging through a collection of data. The good news is that RadDataPager can be used to page any collection. It does not depend on RadGridView in any way, so you will be free to use it with the rest of your ItemsControls if you chose to do so. Before you read on, you might want to download the samples solution that I have attached. It contains a sample project for every scenario that I will discuss later on. Looking at the code while reading will make things much easier for you. There is something for everyone among the 10 Visual Studio projects that are included in the solution. So go and grab it. I. Paging essentials The single most important piece of software concerning paging in Silverlight is the System.ComponentModel.IPagedCollectionView interface. Those of you who are on the WPF front need not worry though. As you might already know, Teleriks Silverlight and WPF controls is share the same code-base. Since WPF does not contain a similar interface, Telerik has provided its own Telerik.Windows.Data.IPagedCollectionView. The IPagedCollectionView interface contains several important members which are used by RadGridView to perform the actual paging. Silverlight provides a default implementation of this interface which, naturally, is called PagedCollectionView. You should definitely take a look at its source code in case you are interested in what is going on under the hood. But this is not a prerequisite for our discussion. The WPF default implementation of the interface is Teleriks QueryableCollectionView which, among many other interfaces, implements IPagedCollectionView. II. No Paging In order to gradually build up my case, I will start with a very simple example that lacks paging whatsoever. It might sound stupid, but this will help us build on top of this paging-devoid example. Let us imagine that we have the simplest possible scenario. That is a simple IEnumerable and an ItemsControl that shows its contents. This will look like this: No Paging IEnumerable itemsSource = Enumerable.Range(0, 1000); this.itemsControl.ItemsSource = itemsSource; XAML <Border Grid.Row="0" BorderBrush="Black" BorderThickness="1" Margin="5">     <ListBox Name="itemsControl"/> </Border> <Border Grid.Row="1" BorderBrush="Black" BorderThickness="1" Margin="5">     <TextBlock Text="No Paging"/> </Border> Nothing special for now. Just some data displayed in a ListBox. The two sample projects in the solution that I have attached are: NoPaging_WPF NoPaging_SL3 With every next sample those two project will evolve in some way or another. III. Paging simple collections The single most important property of RadDataPager is its Source property. This is where you pass in your collection of data for paging. More often than not your collection will not be an IPagedCollectionView. It will either be a simple List<T>, or an ObservableCollection<T>, or anything that is simply IEnumerable. Unless you had paging in mind when you designed your project, it is almost certain that your data source will not be pageable out of the box. So what are the options? III. 1. Wrapping the simple collection in an IPagedCollectionView If you look at the constructors of PagedCollectionView and QueryableCollectionView you will notice that you can pass in a simple IEnumerable as a parameter. Those two classes will wrap it and provide paging capabilities over your original data. In fact, this is what RadGridView does internally. It wraps your original collection in an QueryableCollectionView in order to easily perform many useful tasks such as filtering, sorting, and others, but in our case the most important one is paging. So let us start our series of examples with the most simplistic one. Imagine that you have a simple IEnumerable which is the source for an ItemsControl. Here is how to wrap it in order to enable paging: Silverlight IEnumerable itemsSource = Enumerable.Range(0, 1000); var pagedSource = new PagedCollectionView(itemsSource); this.radDataPager.Source = pagedSource; this.itemsControl.ItemsSource = pagedSource; WPF IEnumerable itemsSource = Enumerable.Range(0, 1000); var pagedSource = new QueryableCollectionView(itemsSource); this.radDataPager.Source = pagedSource; this.itemsControl.ItemsSource = pagedSource; XAML <Border Grid.Row="0"         BorderBrush="Black"         BorderThickness="1"         Margin="5">     <ListBox Name="itemsControl"/> </Border> <Border Grid.Row="1"         BorderBrush="Black"         BorderThickness="1"         Margin="5">     <telerikGrid:RadDataPager Name="radDataPager"                               PageSize="10"                              IsTotalItemCountFixed="True"                              DisplayMode="All"/> This will do the trick. It is quite simple, isnt it? The two sample projects in the solution that I have attached are: PagingSimpleCollectionWithWrapping_WPF PagingSimpleCollectionWithWrapping_SL3 III. 2. Binding to RadDataPager.PagedSource In case you do not like this approach there is a better one. When you assign an IEnumerable as the Source of a RadDataPager it will automatically wrap it in a QueryableCollectionView and expose it through its PagedSource property. From then on, you can attach any number of ItemsControls to the PagedSource and they will be automatically paged. Here is how to do this entirely in XAML: Using RadDataPager.PagedSource <Border Grid.Row="0"         BorderBrush="Black"         BorderThickness="1" Margin="5">     <ListBox Name="itemsControl"              ItemsSource="{Binding PagedSource, ElementName=radDataPager}"/> </Border> <Border Grid.Row="1"         BorderBrush="Black"         BorderThickness="1"         Margin="5">     <telerikGrid:RadDataPager Name="radDataPager"                               Source="{Binding ItemsSource}"                              PageSize="10"                              IsTotalItemCountFixed="True"                              DisplayMode="All"/> The two sample projects in the solution that I have attached are: PagingSimpleCollectionWithPagedSource_WPF PagingSimpleCollectionWithPagedSource_SL3 IV. Paging collections implementing IPagedCollectionView Those of you who are using WCF RIA Services should feel very lucky. After a quick look with Reflector or the debugger we can see that the DomainDataSource.Data property is in fact an instance of the DomainDataSourceView class. This class implements a handful of useful interfaces: ICollectionView IEnumerable INotifyCollectionChanged IEditableCollectionView IPagedCollectionView INotifyPropertyChanged Luckily, IPagedCollectionView is among them which lets you do the whole paging in the server. So lets do this. We will add a DomainDataSource control to our page/window and connect the items control and the pager to it. Here is how to do this: MainPage <riaControls:DomainDataSource x:Name="invoicesDataSource"                               AutoLoad="True"                               QueryName="GetInvoicesQuery">     <riaControls:DomainDataSource.DomainContext>         <services:ChinookDomainContext/>     </riaControls:DomainDataSource.DomainContext> </riaControls:DomainDataSource> <Border Grid.Row="0"         BorderBrush="Black"         BorderThickness="1"         Margin="5">     <ListBox Name="itemsControl"              ItemsSource="{Binding Data, ElementName=invoicesDataSource}"/> </Border> <Border Grid.Row="1"         BorderBrush="Black"         BorderThickness="1"         Margin="5">     <telerikGrid:RadDataPager Name="radDataPager"                               Source="{Binding Data, ElementName=invoicesDataSource}"                              PageSize="10"                              IsTotalItemCountFixed="True"                              DisplayMode="All"/> By the way, you can replace the ListBox from the above code snippet with any other ItemsControl. It can be RadGridView, it can be the MS DataGrid, you name it. Essentially, RadDataPager is sending paging commands to the the DomainDataSource.Data. It does not care who, what, or how many different controls are bound to this same Data property of the DomainDataSource control. So if you would like to experiment with this, you can throw in any number of other ItemsControls next to the ListBox, bind them in the same manner, and all of them will be paged by our single RadDataPager. Furthermore, you can throw in any number of RadDataPagers and bind them to the same property. Then when you page with any one of them will automatically update all of the rest. The whole picture is simply beautiful and we can do all of this thanks to WCF RIA Services. The two sample projects (Silverlight only) in the solution that I have attached are: PagingIPagedCollectionView PagingIPagedCollectionView.Web IV. Paging RadGridView While you can replace the ListBox in any of the above examples with a RadGridView, RadGridView offers something extra. Similar to the DomainDataSource.Data property, the RadGridView.Items collection implements the IPagedCollectionView interface. So you are already thinking: Then why not bind the Source property of RadDataPager to RadGridView.Items? Well thats exactly what you can do and you will start paging RadGridView out-of-the-box. It is as simple as that, no code-behind is involved: MainPage <Border Grid.Row="0"         BorderBrush="Black"         BorderThickness="1" Margin="5">     <telerikGrid:RadGridView Name="radGridView"                              ItemsSource="{Binding ItemsSource}"/> </Border> <Border Grid.Row="1"         BorderBrush="Black"         BorderThickness="1"         Margin="5">     <telerikGrid:RadDataPager Name="radDataPager"                               Source="{Binding Items, ElementName=radGridView}"                              PageSize="10"                              IsTotalItemCountFixed="True"                              DisplayMode="All"/> The two sample projects in the solution that I have attached are: PagingRadGridView_SL3 PagingRadGridView_WPF With this last example I think I have covered every possible paging combination. In case you would like to see an example of something that I have not covered, please let me know. Also, make sure you check out those great online examples: WCF RIA Services with DomainDataSource Paging Configurator Endless Paging Paging Any Collection Paging RadGridView Happy Paging! Download Full Source Code Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • CodePlex Daily Summary for Thursday, March 18, 2010

    CodePlex Daily Summary for Thursday, March 18, 2010New ProjectsBordecal tools for FxCop: Bordecal tools for FxCop provides an extended framework for FxCop rule development. It allows rule developers to avoid using embedded XML resource...DotNetNuke® Skin City: A DotNetNuke Design Challenge skin package submitted to the "Personal" category by allsnnskins. We integrate orange color and black colour in this ...DotNetNuke® Skin Dawn: A DotNetNuke Design Challenge skin package submitted to the "Out of the box" category by allsnnskins. This design reflects the theme of daylight. U...DotNetNuke® Skin Dream: A DotNetNuke Design Challenge skin package submitted to the "Personal" category by WhNuke. Uses the DNNJDMenu skin object.DotNetNuke® Skin Expression: A DotNetNuke Design Challenge skin package submitted to the "Out of the box" category by Salar Golestanian of SalarO. This is a pure CSS skin with ...DotNetNuke® Skin ModernBiz: A DotNetNuke Design Challenge skin package submitted to the "Modern Business" category by allsnnskins. This simple and unaffected company skin uses...DotNetNuke® Skin Profound: A DotNetNuke Design Challenge skin package submitted to the "Modern Business" category by WhNuke Technology. This skin is simple and clean and the ...DotNetNuke® Skin Technology: A DotNetNuke Design Challenge skin package submitted to the "Modern Standards" category by allsnnskins. It's compatible with common browsers such ...DotNetNuke® Skin Unravel: A DotNetNuke Design Challenge skin package submitted to the "Modern Business" category by Salar Golestanian of SalarO. This is a pure CSS skin wit...E! - ECMAScript Runtime Environment: E! (pronounced E-Bang) is a lightweight runtime environment for editing basic ECMAScript scripts with access to .NET Framework class libraries.Easy ArcGIS Library: Easy ArcGIS Library is a set of C# .net classes that wrap the common functionality of ArcObjects, that help ArcGIS developers do a lot of common fu...File Categorizer: The File Categorizer will help people tag the files on their system for easy searching. Instead of keyword searches, you can find files based on v...GMFS Cosmos: This is a file system for Cosmos a OS that was built with C# and we will be implementing this for windows and linuxIFilter Core Implementation (interface and structures): IFilter C# implementation for you to embed when writing Windows Search capabilities into your application.Image Wall Control for Silverlight: A control for Silverlight that emulates the wall of images in the Zune. imenik_za _dev4fun: imenik is a very simple program and easy to use where you can save and organise your contacts.LegoPhysX: LegoPhysX is an atomic based physics enginePersonal Accounting: Personal system for managing financial accounts, which supports multiple accounts in different currencies. It has movement imputation and basic que...Pipes & Filters Engine: The Pipes & Filters Engine allows you to process a sequence of separate operations (filters) asynchronously in a multi-threaded manner. Filters wil...Prerequisites Checker: Check preqrequisites for software. Example: Software S1 is delivered. S1 has prerequisites PR1, PR2... PRN You may load the config file for S...Puzzle Lib: A library for creating grid-and-tile puzzles. Includes two separate UIs for the Tetriminoes puzzle as examples.QuotesPlugin for Windows Live Writer: The QuotesPlugin for Windows Live Writer lists quotes from web sites such as quotes4all.net. It's very easy for you to select your favourite ones a...RobiJ2se: Robi j2se Learning!SkinEngine: This is a Skin Framework for C# Winform, It use easy.and Create Skin GreatSQL Azure .NET Connection: This is a demo application that shows how to connect with SQL AzureSupermarket Soft: WPF Application that helps you manage your supermarket shoppings.Tally Marks for Windows Phone 7 Series: Tally Marks is a counting application. It can count almost anything you'd like to count, and it does it with tally marks! Count the number of peo...TwitCast: TwitCast is a simple notifier for Twitter using the [url:http://linqtotwitter.codeplex.com/] LINQ 2 Twitter library.WodnySwiat: Projekt grupowy wodny światWSS Task Manager Activity: A custom task creation activity that can be used in a sequential or state machine workflow. The activity was specifically developed to handle task ...New ReleasesAddress Book: Address Book: Address BookAutoAudit: AutoAudit 1.10c: Veresion 1.10 includes most of the bug fix requests. adds createdby and modifiedby columns to the audited base tables. If the user name is set by...blog for umbraco 4: Blog 4 Umbraco 2.0.26: Fixes: -Regex bug in base -Directory urls and rss link bug -Open reader bug -Rss bugDotNetNuke® Skin City: City Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Personal" category by allsnnskins. We integrate orange color and black colour in this ...DotNetNuke® Skin Dawn: Dawn Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Out of the box" category by allsnnskins. This design reflects the theme of daylight. U...DotNetNuke® Skin Dream: Dream Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Personal" category by WhNuke. Uses the DNNJDMenu skin object.DotNetNuke® Skin Expression: Expression Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Out of the box" category by Salar Golestanian of SalarO. This is a pure CSS skin with ...DotNetNuke® Skin ModernBiz: ModernBiz Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Modern Business" category by allsnnskins. This simple and unaffected company skin uses...DotNetNuke® Skin Profound: Profound Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Modern Business" category by WhNuke Technology. This skin is simple and clean and the ...DotNetNuke® Skin Technology: Technology Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Modern Standards" category by allsnnskins. It's compatible with common browsers such a...DotNetNuke® Skin Unravel: Unravel Package 1.0.0: A DotNetNuke Design Challenge skin package submitted to the "Modern Business" category by Salar Golestanian of SalarO. This is a pure CSS skin with...E! - ECMAScript Runtime Environment: E! beta 1: This is really meant as a learning project for playing with dynamically compiled code, so you'd be better off getting the source code.Easy ArcGIS Library: EAGL Binaries: Easy ArcGIS Library Last Build (Version 1.1.2.4139)Easy ArcGIS Library: EAGL Binaries And Documentation: EAGL Latest Build With DocumentationEasy ArcGIS Library: EAGL Documentation: EAGL 1.1.2.4139 DocumentationEnterprise Library Extensions: Release 1.1: This is a service release for version 1.0 The installation process now works as intended. The assemblies are now visible in the Visual Studio As...Family Tree Analyzer: Version 1.2.1.0: Version 1.2.1.0 Fixed GB radio button not working renamed UK Added fixes for UK regions/shires/counties where country is missing Add country reco...Family Tree Analyzer: Version 1.3.0.0: Version 1.3.0.0 Added IGI Search results viewer Tweaked filenames of IGI search so that results window has more informative displayFile Archive: File Archive: If your computer is only word processing machine or document merge machine, this program is really fit for you. It's so...o useful! This program ar...GameStore League Manager: League Manager 1.0.4: Fixes bug 7434. Changed version number to the standard format of Major.Minor.ReleaseIFilter Core Implementation (interface and structures): Stable release: First release of interface implementation.IFilter Core Implementation (interface and structures): System.Search.Core: Ifilter interface for implementation in your own Search Providers.imenik_za _dev4fun: imenik_aplikacija: imenik aplikacija is an application easy to use where you can save and organise your contacts.KDRE - kernel debugger regular expression extension: KDRE 0.0.2: KDRE - Windbg regexp extension Changes: - amd64 build addedMapWindow6: MapWindow 6.0 msi (March 17): This release introduces some minor tweaks to the source code exposing more buffering functionality. This also fixes a problem with selecting point...MockingBird: MockingBird_2.0_RC: This is the V2.0 RC release. The documentation includes notes about the WCF components. Check this blog post for more details about the release. ...MPF for Projects - Visual Studio 2010: Visual Studio 2010 - Final Release: This contains the source code for the release of MPF for Projects corresponding to Visual Studio 2010. For Beta 2, you will need the Beta 2 release...Physics Helper for Silverlight, WPF, Blend, and Farseer: PhysicsHelper 3.0.0.4 ALPHA: This is an initial release that supports Windows Phone 7 Series Development, along with the Silverlight 3 and WPF support. It requires Visual Studi...Pocket GPW: Pocket GPW 1.2: Modyfikacje wg. change set-a 56678. Poprzednia baza danych (z wersji 1.1) jest zgodna z aktualną. Przed instalacją skopiuj poprzednią bazę danych ...Prerequisites Checker: Prerequisites Checker: Check your software prerequisitesPuzzle Lib: Puzzle Lib examples: Tetriminoes examples using a common Puzzle LIB and common Puzzle Implementation library, demonstrating a basic MVC architecture for game developmentRoTwee: RoTwee (8.0.7.0): Now you can rotate tweets by your hand !SharePoint Icon Integration: SharePoint Icon Integration PDF: This is the first stable release of the SPIconIntegration. To install the PDF Icon integration just start the setup.exe file that you will find in ...SkinEngine: SkinEngine-Src-2010-03-17: this is a release on 2010-03-17Spell Corrector: Spell Corrector 0.2 Binary: Fixed a bug in the word indexing in the database.Spell Corrector: Spell Corrector 0.2 Code: Fixed a bug in the indexing of the words in the database. Now insertion of new words in the database is faster.SQL Azure .NET Connection: LittleBlackBook.NET Release 1.0: This was a demo project for a SQL Azure Presentation at ConfooSQL Server Extended Properties Quick Editor: New release 1.5.5: Whats new: Move preferences to application settings and add a form to edit preferences. Support to add, modify and delete operations could be made ...SuperModel - A Dynamic View-Model Generator: 1.0.0.1 - Tyra+: Resolving a couple of bugs; models generated using INotifyPropertyChanged were not being created correctly. Property resolution on proxied types w...Survey - web survey & form engine: Survey 1.2.0: The Survey 1.2.0 release is based on the original sources of the Nsurvey 1.9 application. Compared to the Survey 1.1.0 version many new features ...T.S.T. the T-SQL Test Tool: Version 1.5: Version 1.5 changes: Bug fix. In V1.4 and earlier table comparison failed if the tables compared had columns with spaces in them.TwitCast: TwitCast 1.0.0.0: First release of TwitCast. Be warned that this is just a development release and there are a lot of things that remain to be done.unbinder: Unbound.dll: from change set ef6f2303dd32VCC: Latest build, v2.1.30317.0: Automatic drop of latest buildWatchersNET.TagCloud: WatchersNET.TagCloud 01.02.00: Whats New Show only Tags from Pages the Current User has View Acess (As Option) A Url can be specified for a Custom tag Added Module Package fo...WSS Task Manager Activity: 1.0: Download either the source for Moss Task Manager Activity, Workflow sample if you are interested to see how to use the activity in the workflow or ...XML pretty print for python (xmlpp): version 0.92b: Fixes issues when element name contains :Xpress - ASP.NET MVC 个人博客程序: xpress2.1.1.0317.beta: 最新beta版 更改内容: 模板与系统所需配置文件移动到App_Data中 Service对象注入到Controller中 Controller对象放入IOC容器中 邮件发送BUG修正Most Popular ProjectsMetaSharpRawrWBFS ManagerSilverlight ToolkitASP.NET Ajax LibraryMicrosoft SQL Server Product Samples: DatabaseAJAX Control ToolkitLiveUpload to FacebookWindows Presentation Foundation (WPF)ASP.NETMost Active ProjectsLINQ to TwitterRawrOData SDK for PHPDirectQOpen Data App Framework (ODAF)patterns & practices – Enterprise LibraryBlogEngine.NETjQuery Library for SharePoint Web ServicesMapWindow6NB_Store - Free DotNetNuke Ecommerce Catalog Module

    Read the article

  • Read XML Files using LINQ to XML and Extension Methods

    - by psheriff
    In previous blog posts I have discussed how to use XML files to store data in your applications. I showed you how to read those XML files from your project and get XML from a WCF service. One of the problems with reading XML files is when elements or attributes are missing. If you try to read that missing data, then a null value is returned. This can cause a problem if you are trying to load that data into an object and a null is read. This blog post will show you how to create extension methods to detect null values and return valid values to load into your object. The XML Data An XML data file called Product.xml is located in the \Xml folder of the Silverlight sample project for this blog post. This XML file contains several rows of product data that will be used in each of the samples for this post. Each row has 4 attributes; namely ProductId, ProductName, IntroductionDate and Price. <Products>  <Product ProductId="1"           ProductName="Haystack Code Generator for .NET"           IntroductionDate="07/01/2010"  Price="799" />  <Product ProductId="2"           ProductName="ASP.Net Jumpstart Samples"           IntroductionDate="05/24/2005"  Price="0" />  ...  ...</Products> The Product Class Just as you create an Entity class to map each column in a table to a property in a class, you should do the same for an XML file too. In this case you will create a Product class with properties for each of the attributes in each element of product data. The following code listing shows the Product class. public class Product : CommonBase{  public const string XmlFile = @"Xml/Product.xml";   private string _ProductName;  private int _ProductId;  private DateTime _IntroductionDate;  private decimal _Price;   public string ProductName  {    get { return _ProductName; }    set {      if (_ProductName != value) {        _ProductName = value;        RaisePropertyChanged("ProductName");      }    }  }   public int ProductId  {    get { return _ProductId; }    set {      if (_ProductId != value) {        _ProductId = value;        RaisePropertyChanged("ProductId");      }    }  }   public DateTime IntroductionDate  {    get { return _IntroductionDate; }    set {      if (_IntroductionDate != value) {        _IntroductionDate = value;        RaisePropertyChanged("IntroductionDate");      }    }  }   public decimal Price  {    get { return _Price; }    set {      if (_Price != value) {        _Price = value;        RaisePropertyChanged("Price");      }    }  }} NOTE: The CommonBase class that the Product class inherits from simply implements the INotifyPropertyChanged event in order to inform your XAML UI of any property changes. You can see this class in the sample you download for this blog post. Reading Data When using LINQ to XML you call the Load method of the XElement class to load the XML file. Once the XML file has been loaded, you write a LINQ query to iterate over the “Product” Descendants in the XML file. The “select” portion of the LINQ query creates a new Product object for each row in the XML file. You retrieve each attribute by passing each attribute name to the Attribute() method and retrieving the data from the “Value” property. The Value property will return a null if there is no data, or will return the string value of the attribute. The Convert class is used to convert the value retrieved into the appropriate data type required by the Product class. private void LoadProducts(){  XElement xElem = null;   try  {    xElem = XElement.Load(Product.XmlFile);     // The following will NOT work if you have missing attributes    var products =         from elem in xElem.Descendants("Product")        orderby elem.Attribute("ProductName").Value        select new Product        {          ProductId = Convert.ToInt32(            elem.Attribute("ProductId").Value),          ProductName = Convert.ToString(            elem.Attribute("ProductName").Value),          IntroductionDate = Convert.ToDateTime(            elem.Attribute("IntroductionDate").Value),          Price = Convert.ToDecimal(elem.Attribute("Price").Value)        };     lstData.DataContext = products;  }  catch (Exception ex)  {    MessageBox.Show(ex.Message);  }} This is where the problem comes in. If you have any missing attributes in any of the rows in the XML file, or if the data in the ProductId or IntroductionDate is not of the appropriate type, then this code will fail! The reason? There is no built-in check to ensure that the correct type of data is contained in the XML file. This is where extension methods can come in real handy. Using Extension Methods Instead of using the Convert class to perform type conversions as you just saw, create a set of extension methods attached to the XAttribute class. These extension methods will perform null-checking and ensure that a valid value is passed back instead of an exception being thrown if there is invalid data in your XML file. private void LoadProducts(){  var xElem = XElement.Load(Product.XmlFile);   var products =       from elem in xElem.Descendants("Product")      orderby elem.Attribute("ProductName").Value      select new Product      {        ProductId = elem.Attribute("ProductId").GetAsInteger(),        ProductName = elem.Attribute("ProductName").GetAsString(),        IntroductionDate =            elem.Attribute("IntroductionDate").GetAsDateTime(),        Price = elem.Attribute("Price").GetAsDecimal()      };   lstData.DataContext = products;} Writing Extension Methods To create an extension method you will create a class with any name you like. In the code listing below is a class named XmlExtensionMethods. This listing just shows a couple of the available methods such as GetAsString and GetAsInteger. These methods are just like any other method you would write except when you pass in the parameter you prefix the type with the keyword “this”. This lets the compiler know that it should add this method to the class specified in the parameter. public static class XmlExtensionMethods{  public static string GetAsString(this XAttribute attr)  {    string ret = string.Empty;     if (attr != null && !string.IsNullOrEmpty(attr.Value))    {      ret = attr.Value;    }     return ret;  }   public static int GetAsInteger(this XAttribute attr)  {    int ret = 0;    int value = 0;     if (attr != null && !string.IsNullOrEmpty(attr.Value))    {      if(int.TryParse(attr.Value, out value))        ret = value;    }     return ret;  }   ...  ...} Each of the methods in the XmlExtensionMethods class should inspect the XAttribute to ensure it is not null and that the value in the attribute is not null. If the value is null, then a default value will be returned such as an empty string or a 0 for a numeric value. Summary Extension methods are a great way to simplify your code and provide protection to ensure problems do not occur when reading data. You will probably want to create more extension methods to handle XElement objects as well for when you use element-based XML. Feel free to extend these extension methods to accept a parameter which would be the default value if a null value is detected, or any other parameters you wish. NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose “Tips & Tricks”, then "Read XML Files using LINQ to XML and Extension Methods" from the drop-down. Good Luck with your Coding,Paul D. Sheriff  

    Read the article

  • Building a &ldquo;real&rdquo; extension for Expression Blend

    - by Timmy Kokke
    .Last time I showed you how to get started building extensions for Expression Blend. Lets build a useful extension this time and go a bit deeper into Blend. Source of project  => here Compiled dll => here (extract into /extensions folder of Expression Blend)   The Extension When working on large Xaml files in Blend it’s often hard to find a specific control in the "Objects and Timeline Pane”. An extension that searches the active document and presents all elements that satisfy the query would be helpful. When the user starts typing a search query a search will be performed and the results are shown in the list. After the user selects an item in the results list, the control in the "Objects and Timeline Pane” will be selected. Below is a sketch of what it is going to look like. The Solution Create a new WPF User Control project as shown in the earlier tutorial in the Configuring the extension project section, but name it AdvancedSearch this time. Delete the default UserControl1.Xaml to clear the solution (a new user control will be added later thought, but adding a user control is easier then renaming one). Create the main entry point of the addin by adding a new class to the solution and naming this  AdvancedSearchPackage. Add a reference to Microsoft.Expression.Extensibility and to System.ComponentModel.Composition . Implement the IPackage interface and add the Export attribute from the MEF to the definition. While you’re at it. Add references to Microsoft.Expression.DesignSurface, Microsoft.Expression.FrameWork and Microsoft.Expression.Markup. These will be used later. The Load method from the IPackage interface is going to create a ViewModel to bind to from the UI. Add another class to the solution and name this AdvancedSearchViewModel. This class needs to implement the INotifyPropertyChanged interface to enable notifications to the view.  Add a constructor to the class that takes an IServices interface as a parameter. Create a new instance of the AdvancedSearchViewModel in the load method in the AdvanceSearchPackage class. The AdvancedSearchPackage class should looks like this now:   using System.ComponentModel.Composition; using Microsoft.Expression.Extensibility;   namespace AdvancedSearch { [Export(typeof(IPackage))] public class AdvancedSearchPackage:IPackage {   public void Load(IServices services) { new AdvancedSearchViewModel(services); }   public void Unload() { } } }   Add a new UserControl to the project and name this AdvancedSearchView. The View will be created by the ViewModel, which will pass itself to the constructor of the view. Change the constructor of the View to take a AdvancedSearchViewModel object as a parameter. Add a private field to store the ViewModel and set this field in the constructor. Point the DataContext of the view to the ViewModel. The View will look something like this now:   namespace AdvancedSearch { public partial class AdvancedSearchView:UserControl { private readonly AdvancedSearchViewModel _advancedSearchViewModel;   public AdvancedSearchView(AdvancedSearchViewModel advancedSearchViewModel) { _advancedSearchViewModel = advancedSearchViewModel; InitializeComponent(); this.DataContext = _advancedSearchViewModel; } } }   The View is going to be created in the constructor of the ViewModel and stored in a read only property.   public FrameworkElement View { get; private set; }   public AdvancedSearchViewModel(IServices services) { _services = services; View = new AdvancedSearchView(this); } The last thing the solution needs before we’ll wire things up is a new class, PossibleNode. This class will be used later to store the search results. The solution should look like this now:   Adding UI to the UI The extension should build and run now, although nothing is showing up in Blend yet. To enable the user to perform a search query add a TextBox and a ListBox to the AdvancedSearchView.xaml file. I’ve set the rows of the grid too to make them look a little better. Add the TextChanged event to the TextBox and the SelectionChanged event to the ListBox, we’ll need those later on. <Grid> <Grid.RowDefinitions> <RowDefinition Height="32" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <TextBox TextChanged="SearchQueryTextChanged" HorizontalAlignment="Stretch" Margin="4" Name="SearchQuery" VerticalAlignment="Stretch" /> <ListBox SelectionChanged="SearchResultSelectionChanged" HorizontalAlignment="Stretch" Margin="4" Name="SearchResult" VerticalAlignment="Stretch" Grid.Row="1" /> </Grid>   This will create a user interface like: To make the View show up in Blend it has to be registered with the WindowService. The GetService<T> method is used to get services from Blend, which are your entry points into Blend.When writing extensions you will encounter this method very often. In this case we’re asking for an IWindowService interface. The IWindowService interface serves events for changing windows and themes, is used for adding or removing resources and is used for registering and unregistering Palettes. All panes in Blend are palettes and are registered thru the RegisterPalette method. The first parameter passed to this method is a string containing a unique ID for the palette. This ID can be used to get access to the palette later. The second parameter is the View. The third parameter is a title for the pane. This title is shown when the pane is visible. It is also shown in the window menu of Blend. The last parameter is a KeyBinding. I have chosen Ctrl+Shift+F to call the Advanced Search pane. This value is also shown in the window menu of Blend.   services.GetService<IWindowService>().RegisterPalette( "AdvancedSearch", viewModel.View, "Advanced Search", new KeyBinding { Key = Key.F, Modifiers = ModifierKeys.Control | ModifierKeys.Shift } );   You can compiler and run now. After Blend starts you can hit Ctrl+Shift+F or go the windows menu to call the advanced search extension. Searching for controls The search has to be cleared on every change of the active document. The DocumentServices fires an event every time a new document is opened, a document is closed or another document view is selected. Add the following line to the constructor of the ViewModel to handle the ActiveDocumentChanged event:   _services.GetService<IDocumentService>().ActiveDocumentChanged += ActiveDocumentChanged;   And implement the ActiveDocumentChanged method:   private void ActiveDocumentChanged(object sender, DocumentChangedEventArgs e) { }   To get to the contents of the document we first need to get access to the “Objects and Timeline” pane. This pane is registered in the PaletteRegistry in the same way as this extension has registered itself. The palettes are accessible thru an associative array. All you need to provide is the Identifier of the palette you want. The Id of the “Objects and Timeline” pane is “Designer_TimelinePane”. I’ve included a list of the other default panes at the bottom of this article. Each palette has a Content property which can be cast to the type of the pane.   var timelinePane = (TimelinePane)_services.GetService<IWindowService>() .PaletteRegistry["Designer_TimelinePane"] .Content;   Add a private field to the top of the AdvancedSearchViewModel class to store the active SceneViewModel. The SceneViewModel is needed to set the current selection and to get the little icons for the type of control.   private SceneViewModel _activeSceneViewModel;   When the active SceneViewModel changes, the ActiveSceneViewModel is stored in this field. The list of possible nodes is cleared and an PropertyChanged event is fired for this list to notify the UI to clear the list. This will make the eventhandler look like this: private void ActiveDocumentChanged(object sender, DocumentChangedEventArgs e) { var timelinePane = (TimelinePane)_services.GetService<IWindowService>() .PaletteRegistry["Designer_TimelinePane"].Content;   _activeSceneViewModel = timelinePane.ActiveSceneViewModel; PossibleNodes = new List<PossibleNode>(); InvokePropertyChanged("PossibleNodes"); } The PossibleNode class used to store information about the controls found by the search. It’s a dumb data class with only 3 properties, the name of the control, the SceneNode and a brush used for the little icon. The SceneNode is the base class for every possible object you can create in Blend, like Brushes, Controls, Annotations, ResourceDictionaries and VisualStates. The entire PossibleNode class looks like this:   using System.Windows.Media; using Microsoft.Expression.DesignSurface.ViewModel;   namespace AdvancedSearch { public class PossibleNode { public string Name { get; set; } public SceneNode SceneNode { get; set; } public DrawingBrush IconBrush { get; set; } } }   Add these two methods to the AdvancedSearchViewModel class:   public void Search(string searchText) { } public void SelectElement(PossibleNode node){ }   Both these methods are going to be called from the view. The Search method performs the search and updates the PossibleNodes list.  The controls in the active document can be accessed thru TimeLineItemsManager class. This class contains a read only collection of TimeLineItems. By using a Linq query the possible nodes are selected and placed in the PossibleNodes list.   var timelineItemManager = new TimelineItemManager(_activeSceneViewModel); PossibleNodes = new List<PossibleNode>( (from d in timelineItemManager.ItemList where d.DisplayName.ToLowerInvariant().StartsWith( searchText.ToLowerInvariant()) select new PossibleNode() { IconBrush = d.IconBrush, SceneNode = d.SceneNode, Name = d.DisplayName }).ToList() ); InvokePropertyChanged(InternalConst.PossibleNodes);   The Select method is pretty straight forward. It contains two lines.The first to clear the selection. Otherwise the selected element would be added to the current selection. The second line selects the nodes. It is given a new array with the node to be selected.   _activeSceneViewModel.ClearSelections(); _activeSceneViewModel.SelectNodes(new[] { node.SceneNode });   The last thing that needs to be done is to wire the whole thing to the View. The two event handlers just call the Search and SelectElement methods on the ViewModel.   private void SearchQueryTextChanged(object sender, TextChangedEventArgs e) { _advancedSearchViewModel.Search(SearchQuery.Text); }   private void SearchResultSelectionChanged(object sender, SelectionChangedEventArgs e) { if(e.AddedItems.Count>0) { _advancedSearchViewModel.SelectElement(e.AddedItems[0] as PossibleNode); } }   The Listbox has to be bound to the PossibleNodes list and a simple DataTemplate is added to show the selection. The IconWithOverlay control can be found in the Microsoft.Expression.DesignSurface.UserInterface.Timeline.UI namespace in the Microsoft.Expression.DesignSurface assembly. The ListBox should look something like:   <ListBox SelectionChanged="SearchResultSelectionChanged" HorizontalAlignment="Stretch" Margin="4" Name="SearchResult" VerticalAlignment="Stretch" Grid.Row="1" ItemsSource="{Binding PossibleNodes}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <tlui:IconWithOverlay Margin="2,0,10,0" Width="12" Height="12" SourceBrush="{Binding Path=IconBrush, Mode=OneWay}" /> <TextBlock Text="{Binding Name}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>   Compile and run. Inside Blend the extension could look something like below. What’s Next When you’ve got the extension running. Try placing breakpoints in the code and see what else is in there. There’s a lot to explore and build extension on. I personally would love an extension to search for resources. Last but not least, you can download the source of project here.  If you have any questions let me know. If you just want to use this extension, you can download the compiled dll here. Just extract the . zip into the /extensions folder of Expression Blend. Notes Target framework I ran into some issues when using the .NET Framework 4 Client Profile as a target framework. I got some strange error saying certain obvious namespaces could not be found, Microsoft.Expression in my case. If you run into something like this, try setting the target framework to .NET Framework 4 instead of the client version.   Identifiers of default panes Identifier Type Title Designer_TimelinePane TimelinePane Objects and Timeline Designer_ToolPane ToolPane Tools Designer_ProjectPane ProjectPane Projects Designer_DataPane DataPane Data Designer_ResourcePane ResourcePane Resources Designer_PropertyInspector PropertyInspector Properties Designer_TriggersPane TriggersPane Triggers Interaction_Skin SkinView States Designer_AssetPane AssetPane Assets Interaction_Parts PartsPane Parts Designer_ResultsPane ResultsPane Results

    Read the article

  • CodePlex Daily Summary for Thursday, December 02, 2010

    CodePlex Daily Summary for Thursday, December 02, 2010Popular ReleasesChronos WPF: Chronos v2.0 Beta 3: Release notes: Updated introduction document. Updated Visual Studio 2010 Extension (vsix) package. Added horizontal scrolling to the main window TaskBar. Added new styles for ListView, ListViewItem, GridViewColumnHeader, ... Added a new WindowViewModel class (allowing to fetch data). Added a new Navigate method (with several overloads) to the NavigationViewModel class (protected). Reimplemented Task usage for the WorkspaceViewModel.OnDelete method. Removed the reflection effect...MDownloader: MDownloader-0.15.26.7024: Fixed updater; Fixed MegauploadDJ - jQuery WebControls for ASP.NET: DJ 1.2: What is new? Update to support jQuery 1.4.2 Update to support jQuery ui 1.8.6 Update to Visual Studio 2010 New WebControls with samples added Autocomplete WebControl Button WebControl ToggleButt WebControl The example web site is including in source code project.LateBindingApi.Excel: LateBindingApi.Excel Release 0.7g: Unterschiede zur Vorgängerversion: - Zusätzliche Interior Properties - Group / Ungroup Methoden für Range - Bugfix COM Reference Handling für Application Objekt in einigen Klassen Release+Samples V0.7g: - Enthält Laufzeit DLL und Beispielprojekte Beispielprojekte: COMAddinExample - Demonstriert ein versionslos angebundenes COMAddin Example01 - Background Colors und Borders für Cells Example02 - Font Attributes undAlignment für Cells Example03 - Numberformats Example04 - Shapes, WordArts, P...ESRI ArcGIS Silverlight Toolkit: November 2010 - v2.1: ESRI ArcGIS Silverlight Toolkit v2.1 Added Windows Phone 7 build. New controls added: InfoWindow ChildPage (Windows Phone 7 only) See what's new here full details for : http://help.arcgis.com/en/webapi/silverlight/help/#/What_s_new_in_2_1/016600000025000000/ Note: Requires Visual Studio 2010, .NET 4.0 and Silverlight 4.0.ASP .NET MVC CMS (Content Management System): Atomic CMS 2.1.1: Atomic CMS 2.1.1 release notes Atomic CMS installation guide Winware: Winware 3.0 (.Net 4.0): Winware 3.0 is base on .Net 4.0 with C#. Please open it with Visual Studio 2010. This release contains a lab web application.EnhSim: EnhSim 2.1.1: 2.1.1This release adds in the changes for 4.03a. To use this release, you must have the Microsoft Visual C++ 2010 Redistributable Package installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=A7B7A05E-6DE6-4D3A-A423-37BF0912DB84 To use the GUI you must have the .NET 4.0 Framework installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992 - Switched Searing Flames bac...AI: Initial 0.0.1: It’s simply just one code file; it simulates AI and machine in a simulated world. The AI has a little understanding of its body machine and parts, and able to use its feet to do actions just start and stop walking. The world is all of white with nothing but just the machine on a white planet. Colors, odors and position information make no sense. I’m previous C# programmer and I’m learning F# during this project, although I’m still not a good F# programmer, in this project I learning to prog...NKinect: NKinect Preview: Build features: Accelerometer reading Motor serial number property Realtime image update Realtime depth calculation Export to PLY (On demand) Control motor LED Control Kinect tiltMicrosoft - Domain Oriented N-Layered .NET 4.0 App Sample (Microsoft Spain): V1.0 - N-Layer DDD Sample App .NET 4.0: Required Software (Microsoft Base Software needed for Development environment) Visual Studio 2010 RTM & .NET 4.0 RTM (Final Versions) Expression Blend 4 SQL Server 2008 R2 Express/Standard/Enterprise Unity Application Block 2.0 - Published May 5th 2010 http://www.microsoft.com/downloads/en/details.aspx?FamilyID=2D24F179-E0A6-49D7-89C4-5B67D939F91B&displaylang=en http://unity.codeplex.com/releases/view/31277 PEX & MOLES 0.94.51023.0, 29/Oct/2010 - Visual Studio 2010 Power Tools http://re...Sense/Net Enterprise Portal & ECMS: SenseNet 6.0.1 Community Edition: Sense/Net 6.0.1 Community Edition This half year we have been working quite fiercely to bring you the long-awaited release of Sense/Net 6.0. Download this Community Edition to see what we have been up to. These months we have worked on getting the WebCMS capabilities of Sense/Net 6.0 up to par. New features include: New, powerful page and portlet editing experience. HTML and CSS cleanup, new, powerful site skinning system. Upgraded, lightning-fast indexing and query via Lucene. Limita...Minecraft GPS: Minecraft GPS 1.1.1: New Features Compass! New style. Set opacity on main window to allow overlay of Minecraft. Open World in any folder. Fixes Fixed style so listbox won't grow the window size. Fixed open file dialog issue on non-vista kernel machines.DotSpatial: DotSpatial 11-28-2001: This release introduces some exciting improvements. Support for big raster, both in display and changing the scheme. Faster raster scheme creation for all rasters. Caching of the "sample" values so once obtained the raster symbolizer dialog loads faster. Reprojection supported for raster and image classes. Affine transform fully supported for images and rasters, so skewed images are now possible. Projection uses better checks when loading unprojected layers. GDAL raster support f...Virtu: Virtu 0.9.0: Source Requirements.NET Framework 4 Visual Studio 2010 or Visual Studio 2010 Express Silverlight 4 Tools for Visual Studio 2010 Windows Phone 7 Developer Tools (which includes XNA Game Studio 4) Binaries RequirementsSilverlight 4 .NET Framework 4 XNA Framework 4Cropper: 1.9.4: Mostly fixes for issues with a few feature requests. Fixed Issues 2730 & 3638 & 14467 11044 11447 11448 11449 14665 Implemented Features 6123 11581PFC: PFC for PB 11.5: This is just a migration from the 11.0 code. No changes have been made yet (and they are needed) for it to work properly with 11.5.PDF Rider: PDF Rider 0.5: This release does not add any new feature for pdf manipulation, but enables automatic updates checking, so it is reccomended to install it in order to stay updated with next releases. Prerequisites * Microsoft Windows Operating Systems (XP - Vista - 7) * Microsoft .NET Framework 3.5 runtime * A PDF rendering software (i.e. Adobe Reader) that can be opened inside Internet Explorer. Installation instructionsChoose one of the following methods: 1. Download and run the "pdfRider0...BCLExtensions: BCL Extensions v1.0: The files associated with v1.0 of the BCL Extensions library.Microsoft All-In-One Code Framework: Visual Studio 2010 Code Samples 2010-11-25: Code samples for Visual Studio 2010New Projects<geomap/> - Mapping UI Extensions to HTML / XHTML: A extension to HTML that adds support for declaratively adding maps to web applications. Initially there will only be support for Bing Maps, but a plugin API will be available to add other providers.ActiveRecord Provider: AR Provider is a .NET Membership provider implemented in C#, using Castle ActiveRecord for data persistence.AS PhoneBook: PhoneBook is very simple program which helps you to easily save your contacts names, numbers and e-mails. Designed look, easy dashboard, simple codes developed in c#, perfect perfomance...BAFactory Framework: A multipurpose frameworkBaqUP: Log syncronization system.C++ Bitmap Library: The C++ Bitmap Library consists of simple, robust, optimized and portable 24-bit bitmap image processing algorithms for the C++ language. Drag & Drop for SharePoint: Organize your SharePoint document libraries by moving documents using jQuery Multi-Select Drag&Drop (MSDD) functionality. Estoque: Estoque is a Todo-App that comes with TFS integration an sync.FBA Configuration Manager for SharePoint 2010: Setting up Forms Based Authentication in SharePoint 2010 requires updating the web.config file of three web applications. This utility allows you to update all 3 configs in a single click. The updater can also be invoked from PowerShell.Hackathon - DotNetNuke Razor Contact List: This is a simple set of Razor scripts for displaying a contact list in DotNetNuke using profile data.Joselyn Web Toolkit: A JS LibraryKind Of Magic MSBuild Task: MSBuild task to simplify implementation of INotifyPropertyChanged interface. Injects supporting code in property setters: raising PropertyChanged event when value changed. LocalizationLibrary: The Localization Library is a collection of reusable software component that provide support for localization. This library enables you to localize WPF (Windows Presentation Foundation), Silverlight and WP7 (Windows Phone 7) applications.M1Library: Simple home library managernerdcms: nerdcms.PkrClck: I don't have a summary yet.Poplar: Poplar populates trees.Pyxis 2: NETMF based Operating EnvironmentSchifra Reed Solomon Error Correcting Code Library: Schifra is a very robust, highly optimized and extremely configurable Reed-Solomon error correcting code library for both software and IP core based applications with implementations in C++ and VHDL. Sharepoint (WSS 3.0, MOSS 2007) Reference Samples: A project that contains Sharepoint (WSS 3.0, MOSS 2007) Reference Samples including Custom Site Definition Feature, Custom List View Web Part Feature, List Event Receiver Feature with Feature Receiver, and Custom Theme Feature.Sharepoint 2010 Reset Version Number: Two workflows for SharePoint 2010 which will renumber the versions of an item depending on your needs.Silverlight Control Templates: Replace the default look of Silverlight controls with animated templates.TeamBuy???: ASP.NET????The C++ String Toolkit Library: The C++ String Toolkit Library (StrTk) consists of robust, optimized and portable string processing algorithms for the C++ language. StrTk is designed to be easy to use and integrate within existing code bases. The E2 Compiler and Simulator: The E2 compiler and simulator.tinymceaspdotnet: TinyMceEditor with image uploaderTwinkle Tasks: Twinkle Tasks (TT) is a file based work item tracking (WIT) system designed to work on the command prompt in conjunction with Distributed Version Control Systems (DVCS), such as Mercurial and GIT. UserVoice Helper for WebMatrix: The UserVoice Helper for WebMatrix and ASP.NET Web Pages allows you to easily add UserVoice feedback functionality to your site. Helper also wraps several public API calls. web pejsci: Jedna se o jednoduchy web o psech, s jednoduchym administracnim rozhranim v ASP.NETWykobi Computational Geometry Library: Wykobi is an efficient, robust and simple to use multi-platform 2D/3D computational geometry library. Wykobi provides a concise, predictable, and deterministic interface for geometric primitives and complex geometric routines using and conforming to the ISO/IEC 14882:2003 C++ lanXL5 Module Sheet Converter: This is for workbooks that contain Excel5/95 Module sheets that require the VBA Converter Pack HotFix download to open (see Microsoft KB 926430). It exports the XL5 Module Sheets, removes them and then imports them back in as a Visual Basic Editor modules.????: ?????????????????,??????????????????,?????????????????,?????,?????????????????????????,??????????????????????????????。 ?????OAuth, ?????.Net Framework4.0, ?????C# ???????????,????????????,???????????。

    Read the article

  • Binding collection indexes to a WPF DataGrid at runtime

    - by bearda
    After trying to develop our own control to display a table of data we stumbled on the WPF toolkit DataGrid and thought we were saved. A couple hours later I'm scratching my head trying to figure out if it can do what we really want it to do. The DataGrid seems to be based on displaying various properties of a single object, where I think I need something that can display a collection's items, I want to display a table of strings with a variable number of rows and a variable number of columns. Each row represents the state of a number of inputs at a given time. The number of samples may change, and the number of inputs may change at runtime. As a result, I can't create a custom object that represents a row with a property for each input. This makes the DataGrid binding more complicated, since I can't bind to a fixed property for each column. I thought I found a workaround for this by binding to ".[" + channelIndex + ]" but it hasn't worked out quite the way I wanted. Right now I have a collection of a collection of strings that represents the two-dimensional array of strings. I'm using ObservableCollection so string change event notifications work, but I can use any collection type needed. It looked like everything was working great until I realized that every row was showing the same line of data. Binding in C# is not my strong suit, so I'm kind of lost on what's going wrong. Is what I'm trying to do overall even possible with the WPF Toolkit DataGrid? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Windows.Controls; using System.ComponentModel; using System.Collections; using System.Collections.ObjectModel; namespace WRE.NGDAS.UILayer { /// <summary> /// Interaction logic for DataTableControl.xaml /// </summary> public partial class DataTableControl : UserControl { #region Constants private const int lineHeight = 25; #endregion #region Type Definitions private class TableChannelInfo { internal string ChannelName = string.Empty; internal int Column = 0; public override string ToString() { return ChannelName; } } internal class NotifyString : INotifyPropertyChanged { private string text = String.Empty; public event PropertyChangedEventHandler PropertyChanged; public string Text { get { return text; } set { text = value; NotifyPropertyChanged( "Text" ); } } public NotifyString(string newText) { text = newText; } protected void NotifyPropertyChanged( string propertyChanged ) { if ( PropertyChanged != null ) { PropertyChanged(this, new PropertyChangedEventArgs(propertyChanged)); } } } #endregion #region Private Data Members string[] channels = null; int numberFixed = 0; int numberOfRows = 0; ObservableCollection<ObservableCollection<NotifyString>> tableText = null; #endregion public DataTableControl( List<string> channelNames, List<string> nameToolTips, int numberFixedColumns, int numberRows ) { InitializeComponent(); numberFixed = numberFixedColumns; numberOfRows = numberRows; tableText = new ObservableCollection<ObservableCollection<NotifyString>>(); dataGrid.ItemsSource = tableText; channels = new string[channelNames.Count]; for (int channelIndex = 0; channelIndex < channelNames.Count; channelIndex++) { channels[channelIndex] = channelNames[channelIndex]; tableText.Add(new ObservableCollection<NotifyString>()); for (int i = 0; i < numberOfRows; i++) { tableText[channelIndex].Add( new NotifyString(String.Empty) ); } Binding textBinding = new Binding( ".[" + channelIndex + "]" ); textBinding.Mode = BindingMode.OneWay; textBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; textBinding.Source = tableText[channelIndex]; DataGridTextColumn newColumn = new DataGridTextColumn(); newColumn.Header = channelNames[channelIndex]; newColumn.DisplayIndex = channelIndex; newColumn.Binding = textBinding; if ( channelIndex < numberFixed ) { newColumn.CanUserReorder = false; } dataGrid.Columns.Add(newColumn); } //Height = lineHeight + numberOfRows * lineHeight; } internal void UpdateChannelRow( int rowNumber, List<string> channelValues, DisplayColors color ) { if ( rowNumber < numberOfRows ) { for (int column = 0; column < channelValues.Count; column++) { if ( column < channels.GetLength(0) ) { tableText[column][rowNumber].Text = channelValues[column]; } } } } } }

    Read the article

  • Silverlight Chat WrapPanel Crash / Bug

    - by Matt
    I've been given the task to create a simple Silverlight chat box for two people. My control must adhere to the following requirements Scrollable Text must wrap if it's too long When a new item / message is added it must scroll that item into view Now I've successfully made a usercontrol to meet these requirements, but I've run into a possible bug / crash that I can't for the life of me fix. I'm looking for either a fix to the bug, or a different approach to creating a scrollable chat control. Here's the code I've been using. We'll start with my XAML for the chat window <ListBox x:Name="lbChatHistory" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Disabled" > <ListBox.ItemTemplate> <DataTemplate> <Grid Background="Beige"> <Grid.ColumnDefinitions> <ColumnDefinition Width="70"></ColumnDefinition> <ColumnDefinition Width="Auto"></ColumnDefinition> </Grid.ColumnDefinitions> <TextBlock x:Name="lblPlayer" Foreground="{Binding ForeColor}" Text="{Binding Player}" Grid.Column="0"></TextBlock> <ContentPresenter Grid.Column="1" Width="200" Content="{Binding Message}" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> The idea is to add a new Item to the listbox. The Item (as layed out in the XAML) is a simple 2 column grid. One column for the username, and one column for the message. Now the "items" that I add to the ListBox is a custom class. It has three properties (Player, ForeColor, and Message) that I using binding on within my XAML Player is a string of the current user to display. ForeColor is just a foreground color preference. It helps distinguish the difference between messages. Message is a WrapPanel. I programmatically break the supplied string on the white space for each word. Then for each word, I add a new TextBlock element to the WrapPanel Here is the custom class. public class ChatMessage :DependencyObject, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static DependencyProperty PlayerProperty = DependencyProperty.Register( "Player", typeof( string ), typeof( ChatMessage ), new PropertyMetadata( new PropertyChangedCallback( OnPlayerPropertyChanged ) ) ); public static DependencyProperty MessageProperty = DependencyProperty.Register( "Message", typeof( WrapPanel ), typeof( ChatMessage ), new PropertyMetadata( new PropertyChangedCallback( OnMessagePropertyChanged ) ) ); public static DependencyProperty ForeColorProperty = DependencyProperty.Register( "ForeColor", typeof( SolidColorBrush ), typeof( ChatMessage ), new PropertyMetadata( new PropertyChangedCallback( OnForeColorPropertyChanged ) ) ); private static void OnForeColorPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e ) { ChatMessage c = d as ChatMessage; c.ForeColor = ( SolidColorBrush ) e.NewValue; } public ChatMessage() { Message = new WrapPanel(); ForeColor = new SolidColorBrush( Colors.White ); } private static void OnMessagePropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e ) { ChatMessage c = d as ChatMessage; c.Message = ( WrapPanel ) e.NewValue; } private static void OnPlayerPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e ) { ChatMessage c = d as ChatMessage; c.Player = e.NewValue.ToString(); } public SolidColorBrush ForeColor { get { return ( SolidColorBrush ) GetValue( ForeColorProperty ); } set { SetValue( ForeColorProperty, value ); if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs( "ForeColor" )); } } public string Player { get { return ( string ) GetValue( PlayerProperty ); } set { SetValue( PlayerProperty, value ); if ( PropertyChanged != null ) PropertyChanged( this, new PropertyChangedEventArgs( "Player" ) ); } } public WrapPanel Message { get { return ( WrapPanel ) GetValue( MessageProperty ); } set { SetValue( MessageProperty, value ); if ( PropertyChanged != null ) PropertyChanged( this, new PropertyChangedEventArgs( "Message" ) ); } } } Lastly I add my items to the ListBox. Here's the simple method. It takes the above ChatMessage class as a parameter public void AddChatItem( ChatMessage msg ) { lbChatHistory.Items.Add( msg ); lbChatHistory.ScrollIntoView( msg ); } Now I've tested this and it all works. The problem I'm getting is when I use the scroll bar. You can scroll down using the side scroll bar or arrow keys, but when you scroll up Silverlight crashes. FireBug returns a ManagedRuntimeError #4004 with a XamlParseException. I'm soo close to having this control work, I can taste it! Any thoughts on what I should do or change? Is there a better approach than the one I've taken? Thanks in advance. UPDATE I've found an alternative solution using a ScrollViewer and an ItemsControl instead of a ListBox control. For the most part it's stable.

    Read the article

  • Help with InvalidCastException

    - by Robert
    I have a gridview and, when a record is double-clicked, I want it to open up a new detail-view form for that particular record. As an example, I have created a Customer class: using System; using System.Data; using System.Configuration; using System.Collections.Generic; using System.ComponentModel; using System.Data.SqlClient; using System.Collections; namespace SyncTest { #region Customer Collection public class CustomerCollection : BindingListView<Customer> { public CustomerCollection() : base() { } public CustomerCollection(List<Customer> customers) : base(customers) { } public CustomerCollection(DataTable dt) { foreach (DataRow oRow in dt.Rows) { Customer c = new Customer(oRow); this.Add(c); } } } #endregion public class Customer : INotifyPropertyChanged, IEditableObject, IDataErrorInfo { private string _CustomerID; private string _CompanyName; private string _ContactName; private string _ContactTitle; private string _OldCustomerID; private string _OldCompanyName; private string _OldContactName; private string _OldContactTitle; private bool _Editing; private string _Error = string.Empty; private EntityStateEnum _EntityState; private Hashtable _PropErrors = new Hashtable(); public event PropertyChangedEventHandler PropertyChanged; private void FirePropertyChangeNotification(string propName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } public Customer() { this.EntityState = EntityStateEnum.Unchanged; } public Customer(DataRow dr) { //Populates the business object item from a data row this.CustomerID = dr["CustomerID"].ToString(); this.CompanyName = dr["CompanyName"].ToString(); this.ContactName = dr["ContactName"].ToString(); this.ContactTitle = dr["ContactTitle"].ToString(); this.EntityState = EntityStateEnum.Unchanged; } public string CustomerID { get { return _CustomerID; } set { _CustomerID = value; FirePropertyChangeNotification("CustomerID"); } } public string CompanyName { get { return _CompanyName; } set { _CompanyName = value; FirePropertyChangeNotification("CompanyName"); } } public string ContactName { get { return _ContactName; } set { _ContactName = value; FirePropertyChangeNotification("ContactName"); } } public string ContactTitle { get { return _ContactTitle; } set { _ContactTitle = value; FirePropertyChangeNotification("ContactTitle"); } } public Boolean IsDirty { get { return ((this.EntityState != EntityStateEnum.Unchanged) || (this.EntityState != EntityStateEnum.Deleted)); } } public enum EntityStateEnum { Unchanged, Added, Deleted, Modified } void IEditableObject.BeginEdit() { if (!_Editing) { _OldCustomerID = _CustomerID; _OldCompanyName = _CompanyName; _OldContactName = _ContactName; _OldContactTitle = _ContactTitle; } this.EntityState = EntityStateEnum.Modified; _Editing = true; } void IEditableObject.CancelEdit() { if (_Editing) { _CustomerID = _OldCustomerID; _CompanyName = _OldCompanyName; _ContactName = _OldContactName; _ContactTitle = _OldContactTitle; } this.EntityState = EntityStateEnum.Unchanged; _Editing = false; } void IEditableObject.EndEdit() { _Editing = false; } public EntityStateEnum EntityState { get { return _EntityState; } set { _EntityState = value; } } string IDataErrorInfo.Error { get { return _Error; } } string IDataErrorInfo.this[string columnName] { get { return (string)_PropErrors[columnName]; } } private void DataStateChanged(EntityStateEnum dataState, string propertyName) { //Raise the event if (PropertyChanged != null && propertyName != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } //If the state is deleted, mark it as deleted if (dataState == EntityStateEnum.Deleted) { this.EntityState = dataState; } if (this.EntityState == EntityStateEnum.Unchanged) { this.EntityState = dataState; } } } } Here is my the code for the double-click event: private void customersDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { Customer oCustomer = (Customer)customersBindingSource.CurrencyManager.List[customersBindingSource.CurrencyManager.Position]; CustomerForm oForm = new CustomerForm(); oForm.NewCustomer = oCustomer; oForm.ShowDialog(this); oForm.Dispose(); oForm = null; } Unfortunately, when this code runs, I receive an InvalidCastException error stating "Unable to cast object to type 'System.Data.DataRowView' to type 'SyncTest.Customer'". This error occurs on the very first line of that event: Customer oCustomer = (Customer)customersBindingSource.CurrencyManager.List[customersBindingSource.CurrencyManager.Position]; What am I doing wrong?... and what can I do to fix this? Any help is greatly appreciated. Thanks!

    Read the article

  • MVVM - implementing 'IsDirty' functionality to a ModelView in order to save data

    - by Brendan
    Hi, Being new to WPF & MVVM I struggling with some basic functionality. Let me first explain what I am after, and then attach some example code... I have a screen showing a list of users, and I display the details of the selected user on the right-hand side with editable textboxes. I then have a Save button which is DataBound, but I would only like this button to display when data has actually changed. ie - I need to check for "dirty data". I have a fully MVVM example in which I have a Model called User: namespace Test.Model { class User { public string UserName { get; set; } public string Surname { get; set; } public string Firstname { get; set; } } } Then, the ViewModel looks like this: using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Windows.Input; using Test.Model; namespace Test.ViewModel { class UserViewModel : ViewModelBase { //Private variables private ObservableCollection<User> _users; RelayCommand _userSave; //Properties public ObservableCollection<User> User { get { if (_users == null) { _users = new ObservableCollection<User>(); //I assume I need this Handler, but I am stuggling to implement it successfully //_users.CollectionChanged += HandleChange; //Populate with users _users.Add(new User {UserName = "Bob", Firstname="Bob", Surname="Smith"}); _users.Add(new User {UserName = "Smob", Firstname="John", Surname="Davy"}); } return _users; } } //Not sure what to do with this?!?! //private void HandleChange(object sender, NotifyCollectionChangedEventArgs e) //{ // if (e.Action == NotifyCollectionChangedAction.Remove) // { // foreach (TestViewModel item in e.NewItems) // { // //Removed items // } // } // else if (e.Action == NotifyCollectionChangedAction.Add) // { // foreach (TestViewModel item in e.NewItems) // { // //Added items // } // } //} //Commands public ICommand UserSave { get { if (_userSave == null) { _userSave = new RelayCommand(param => this.UserSaveExecute(), param => this.UserSaveCanExecute); } return _userSave; } } void UserSaveExecute() { //Here I will call my DataAccess to actually save the data } bool UserSaveCanExecute { get { //This is where I would like to know whether the currently selected item has been edited and is thus "dirty" return false; } } //constructor public UserViewModel() { } } } The "RelayCommand" is just a simple wrapper class, as is the "ViewModelBase". (I'll attach the latter though just for clarity) using System; using System.ComponentModel; namespace Test.ViewModel { public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable { protected ViewModelBase() { } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } public void Dispose() { this.OnDispose(); } protected virtual void OnDispose() { } } } Finally - the XAML <Window x:Class="Test.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:Test.ViewModel" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <vm:UserViewModel/> </Window.DataContext> <Grid> <ListBox Height="238" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="197" ItemsSource="{Binding Path=User}" IsSynchronizedWithCurrentItem="True"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Path=Firstname}"/> <TextBlock Text="{Binding Path=Surname}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <Label Content="Username" Height="28" HorizontalAlignment="Left" Margin="232,16,0,0" Name="label1" VerticalAlignment="Top" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="323,21,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=User/UserName}" /> <Label Content="Surname" Height="28" HorizontalAlignment="Left" Margin="232,50,0,0" Name="label2" VerticalAlignment="Top" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="323,52,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" Text="{Binding Path=User/Surname}" /> <Label Content="Firstname" Height="28" HorizontalAlignment="Left" Margin="232,84,0,0" Name="label3" VerticalAlignment="Top" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="323,86,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" Text="{Binding Path=User/Firstname}" /> <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="368,159,0,0" Name="button1" VerticalAlignment="Top" Width="75" Command="{Binding Path=UserSave}" /> </Grid> </Window> So basically, when I edit a surname, the Save button should be enabled; and if I undo my edit - well then it should be Disabled again as nothing has changed. I have seen this in many examples, but have not yet found out how to do it. Any help would be much appreciated! Brendan

    Read the article

  • LevelToVisibilityConverter in silverligt 4

    - by prince23
    <UserControl x:Class="SLGridImage.MainPage" 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" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"> <UserControl.Resources> <local:LevelToVisibilityConverter x:Key="LevelToVisibility" /> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <sdk:DataGrid x:Name="dgMarks" CanUserResizeColumns="False" SelectionMode="Single" AutoGenerateColumns="False" VerticalAlignment="Top" ItemsSource="{Binding MarkCollection}" IsReadOnly="True" Margin="13,44,0,0" RowDetailsVisibilityMode="Collapsed" Height="391" HorizontalAlignment="Left" Width="965" VerticalScrollBarVisibility="Visible" > <sdk:DataGrid.Columns> <sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button x:Name="myButton" Click="myButton_Click"> <StackPanel Orientation="Horizontal"> <Image Margin="2, 2, 2, 2" x:Name="imgMarks" Stretch="Fill" Width="12" Height="12" Source="Images/test.png" VerticalAlignment="Center" HorizontalAlignment="Center" Visibility="{Binding Level, Converter={StaticResource LevelToVisibility}}" /> <TextBlock Text="{Binding Level}" TextWrapping="NoWrap" ></TextBlock> </StackPanel> </Button> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn Header="Name" > <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate > <Border> <TextBlock Text="{Binding Name}" /> </Border> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn Header="Marks" Width="80"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Border> <TextBlock Text="{Binding Marks}" /> </Border> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> </sdk:DataGrid.Columns> </sdk:DataGrid> </Grid> </UserControl> in .cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Collections.ObjectModel; using System.ComponentModel; namespace SLGridImage { public partial class MainPage : UserControl { private MarksViewModel model = new MarksViewModel(); public MainPage() { InitializeComponent(); this.DataContext = model; } private void myButton_Click(object sender, RoutedEventArgs e) { } } public class MarksViewModel : INotifyPropertyChanged { public MarksViewModel() { markCollection.Add(new Mark() { Name = "ABC", Marks = 23, Level = 0 }); markCollection.Add(new Mark() { Name = "XYZ", Marks = 67, Level = 1 }); markCollection.Add(new Mark() { Name = "YU", Marks = 56, Level = 0 }); markCollection.Add(new Mark() { Name = "AAA", Marks = 89, Level = 1 }); } private ObservableCollection<Mark> markCollection = new ObservableCollection<Mark>(); public ObservableCollection<Mark> MarkCollection { get { return this.markCollection; } set { this.markCollection = value; OnPropertyChanged("MarkCollection"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propName) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } public class Mark { public string Name { get; set; } public int Marks { get; set; } public int Level { get; set; } } public class LevelToVisibilityConverter : System.Windows.Data.IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Visibility isVisible = Visibility.Collapsed; if ((value == null)) return isVisible; int condition = (int)value; isVisible = condition == 1 ? Visibility.Visible : Visibility.Collapsed; return isVisible; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } } when i run getting error The type 'local:LevelToVisibilityConverter' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. what i am i missing here looking forward for an solution thank you

    Read the article

  • listbox isSelected databinding in DataTemplate

    - by Kinmarui
    I try to simply databind IsSelected property with IsSelected field in my class. But after I change the value in code its doesn't change the property, neither does clicking on ListBoxItem change the field value. XAML: <FlipView ItemsSource="{Binding Source={StaticResource itemsViewSource}}" ... > <FlipView.ItemTemplate> <DataTemplate> <UserControl Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates"> <!-- other controls --> <ListBox Grid.Row="1" Grid.ColumnSpan="3" SelectionMode="Multiple" VerticalAlignment="Center" ItemsSource="{Binding Answers}"> <ListBox.Resources> <local:LogicToText x:Key="logToText" /> </ListBox.Resources> <!-- bind IsSelected only in one way from code to content --> <ItemsControl.ItemTemplate> <DataTemplate> <ListBoxItem IsSelected="{Binding IsSelected, Mode=TwoWay, Converter={StaticResource logToText}}" Content="{Binding IsSelected, Mode=TwoWay, Converter={StaticResource logToText}}"> </ListBoxItem> </DataTemplate> </ItemsControl.ItemTemplate> <!-- not working at all <ListBox.Resources> <Style TargetType="ListBoxItem"> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/> <Setter Property="Content" Value="{Binding IsSelected, Mode=TwoWay}"/> </Style> </ListBox.Resources>--> </ListBox> </UserControl> </DataTemplate> </FlipView.ItemTemplate> </FlipView> Code: Answers private ObservableCollection<PrawoJazdyDataAnswer> _answers = new ObservableCollection<PrawoJazdyDataAnswer>(); public ObservableCollection<PrawoJazdyDataAnswer> Answers { get { return this._answers; } } Single item(Answer) public class PrawoJazdyDataAnswer : NPCHelper// PrawoJazdy.Common.BindableBase { public PrawoJazdyDataAnswer(String ans, bool ansb) { this._ans = ans; this._isSelected = ansb; } public override string ToString() { return _isSelected.ToString(); } //Only For debug purposes normally return _ans; private string _ans; public string Ans { get { return this._ans; } //set { this.SetProperty(ref this._ans, value); } } private bool _isSelected; public bool IsSelected { get { return this._isSelected; } set { _isSelected = value; FirePropertyChanged("IsSelected"); //this.SetProperty(ref this._isSelected, value); } } } FirePropertyChanged public class NPCHelper : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void FirePropertyChanged(string prop) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } Converter(which sometimes seems to be needed and others not..., I tried ~10 approaches from different tutorials/examples) public class LogicToText : IValueConverter { /// <summary> /// /// </summary> public object Convert(object value, Type targetType, object parameter, string language) { //if (value == null || (bool)value == false) // return "False"; return value.ToString(); } /// <summary> /// /// </summary> public object ConvertBack(object value, Type targetType, object parameter, string language) { return value.ToString().Contains("True") ? true : false; } Thanks in advance, and sorry for my English(still learning). @edit Thanks for quick reply. For test purposes i created a button and text block: It's in other controls part (above list box, but in FlipView) <Button Click="spr" >Sprawdz</Button> <TextBlock Text="{Binding Answers[0].IsSelected, Mode=TwoWay}" > </TextBlock> Click method private void spr(object sender, RoutedEventArgs e) { var ans = ((PrawoJazdyDataQuestion)this.flipView.SelectedItem).Answers; foreach (var item in ans) item.IsSelected = item.IsSelected ? false : true; } As I wrote when i'm changing data from code side its change text, but not appearance of ListBoxItem, and if i just select it on ListBox its doesn't change the date i textblock neither in ListBox itself.

    Read the article

  • Entity Framework Code-First, OData & Windows Phone Client

    - by Jon Galloway
    Entity Framework Code-First is the coolest thing since sliced bread, Windows  Phone is the hottest thing since Tickle-Me-Elmo and OData is just too great to ignore. As part of the Full Stack project, we wanted to put them together, which turns out to be pretty easy… once you know how.   EF Code-First CTP5 is available now and there should be very few breaking changes in the release edition, which is due early in 2011.  Note: EF Code-First evolved rapidly and many of the existing documents and blog posts which were written with earlier versions, may now be obsolete or at least misleading.   Code-First? With traditional Entity Framework you start with a database and from that you generate “entities” – classes that bridge between the relational database and your object oriented program. With Code-First (Magic-Unicorn) (see Hanselman’s write up and this later write up by Scott Guthrie) the Entity Framework looks at classes you created and says “if I had created these classes, the database would have to have looked like this…” and creates the database for you! By deriving your entity collections from DbSet and exposing them via a class that derives from DbContext, you "turn on" database backing for your POCO with a minimum of code and no hidden designer or configuration files. POCO == Plain Old CLR Objects Your entity objects can be used throughout your applications - in web applications, console applications, Silverlight and Windows Phone applications, etc. In our case, we'll want to read and update data from a Windows Phone client application, so we'll expose the entities through a DataService and hook the Windows Phone client application to that data via proxies.  Piece of Pie.  Easy as cake. The Demo Architecture To see this at work, we’ll create an ASP.NET/MVC application which will act as the host for our Data Service.  We’ll create an incredibly simple data layer using EF Code-First on top of SQLCE4 and we’ll expose the data in a WCF Data Service using the oData protocol.  Our Windows Phone 7 client will instantiate  the data context via a URI and load the data asynchronously. Setting up the Server project with MVC 3, EF Code First, and SQL CE 4 Create a new application of type ASP.NET MVC 3 and name it DeadSimpleServer.  We need to add the latest SQLCE4 and Entity Framework Code First CTP's to our project. Fortunately, NuGet makes that really easy. Open the Package Manager Console (View / Other Windows / Package Manager Console) and type in "Install-Package EFCodeFirst.SqlServerCompact" at the PM> command prompt. Since NuGet handles dependencies for you, you'll see that it installs everything you need to use Entity Framework Code First in your project. PM> install-package EFCodeFirst.SqlServerCompact 'SQLCE (= 4.0.8435.1)' not installed. Attempting to retrieve dependency from source... Done 'EFCodeFirst (= 0.8)' not installed. Attempting to retrieve dependency from source... Done 'WebActivator (= 1.0.0.0)' not installed. Attempting to retrieve dependency from source... Done You are downloading SQLCE from Microsoft, the license agreement to which is available at http://173.203.67.148/licenses/SQLCE/EULA_ENU.rtf. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device. Successfully installed 'SQLCE 4.0.8435.1' You are downloading EFCodeFirst from Microsoft, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=206497. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device. Successfully installed 'EFCodeFirst 0.8' Successfully installed 'WebActivator 1.0.0.0' You are downloading EFCodeFirst.SqlServerCompact from Microsoft, the license agreement to which is available at http://173.203.67.148/licenses/SQLCE/EULA_ENU.rtf. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device. Successfully installed 'EFCodeFirst.SqlServerCompact 0.8' Successfully added 'SQLCE 4.0.8435.1' to EfCodeFirst-CTP5 Successfully added 'EFCodeFirst 0.8' to EfCodeFirst-CTP5 Successfully added 'WebActivator 1.0.0.0' to EfCodeFirst-CTP5 Successfully added 'EFCodeFirst.SqlServerCompact 0.8' to EfCodeFirst-CTP5 Note: We're using SQLCE 4 with Entity Framework here because they work really well together from a development scenario, but you can of course use Entity Framework Code First with other databases supported by Entity framework. Creating The Model using EF Code First Now we can create our model class. Right-click the Models folder and select Add/Class. Name the Class Person.cs and add the following code: using System.Data.Entity; namespace DeadSimpleServer.Models { public class Person { public int ID { get; set; } public string Name { get; set; } } public class PersonContext : DbContext { public DbSet<Person> People { get; set; } } } Notice that the entity class Person has no special interfaces or base class. There's nothing special needed to make it work - it's just a POCO. The context we'll use to access the entities in the application is called PersonContext, but you could name it anything you wanted. The important thing is that it inherits DbContext and contains one or more DbSet which holds our entity collections. Adding Seed Data We need some testing data to expose from our service. The simplest way to get that into our database is to modify the CreateCeDatabaseIfNotExists class in AppStart_SQLCEEntityFramework.cs by adding some seed data to the Seed method: protected virtual void Seed( TContext context ) { var personContext = context as PersonContext; personContext.People.Add( new Person { ID = 1, Name = "George Washington" } ); personContext.People.Add( new Person { ID = 2, Name = "John Adams" } ); personContext.People.Add( new Person { ID = 3, Name = "Thomas Jefferson" } ); personContext.SaveChanges(); } The CreateCeDatabaseIfNotExists class name is pretty self-explanatory - when our DbContext is accessed and the database isn't found, a new one will be created and populated with the data in the Seed method. There's one more step to make that work - we need to uncomment a line in the Start method at the top of of the AppStart_SQLCEEntityFramework class and set the context name, as shown here, public static class AppStart_SQLCEEntityFramework { public static void Start() { DbDatabase.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0"); // Sets the default database initialization code for working with Sql Server Compact databases // Uncomment this line and replace CONTEXT_NAME with the name of your DbContext if you are // using your DbContext to create and manage your database DbDatabase.SetInitializer(new CreateCeDatabaseIfNotExists<PersonContext>()); } } Now our database and entity framework are set up, so we can expose data via WCF Data Services. Note: This is a bare-bones implementation with no administration screens. If you'd like to see how those are added, check out The Full Stack screencast series. Creating the oData Service using WCF Data Services Add a new WCF Data Service to the project (right-click the project / Add New Item / Web / WCF Data Service). We’ll be exposing all the data as read/write.  Remember to reconfigure to control and minimize access as appropriate for your own application. Open the code behind for your service. In our case, the service was called PersonTestDataService.svc so the code behind class file is PersonTestDataService.svc.cs. using System.Data.Services; using System.Data.Services.Common; using System.ServiceModel; using DeadSimpleServer.Models; namespace DeadSimpleServer { [ServiceBehavior( IncludeExceptionDetailInFaults = true )] public class PersonTestDataService : DataService<PersonContext> { // This method is called only once to initialize service-wide policies. public static void InitializeService( DataServiceConfiguration config ) { config.SetEntitySetAccessRule( "*", EntitySetRights.All ); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; config.UseVerboseErrors = true; } } } We're enabling a few additional settings to make it easier to debug if you run into trouble. The ServiceBehavior attribute is set to include exception details in faults, and we're using verbose errors. You can remove both of these when your service is working, as your public production service shouldn't be revealing exception information. You can view the output of the service by running the application and browsing to http://localhost:[portnumber]/PersonTestDataService.svc/: <service xml:base="http://localhost:49786/PersonTestDataService.svc/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app"> <workspace> <atom:title>Default</atom:title> <collection href="People"> <atom:title>People</atom:title> </collection> </workspace> </service> This indicates that the service exposes one collection, which is accessible by browsing to http://localhost:[portnumber]/PersonTestDataService.svc/People <?xml version="1.0" encoding="iso-8859-1" standalone="yes"?> <feed xml:base=http://localhost:49786/PersonTestDataService.svc/ xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom"> <title type="text">People</title> <id>http://localhost:49786/PersonTestDataService.svc/People</id> <updated>2010-12-29T01:01:50Z</updated> <link rel="self" title="People" href="People" /> <entry> <id>http://localhost:49786/PersonTestDataService.svc/People(1)</id> <title type="text"></title> <updated>2010-12-29T01:01:50Z</updated> <author> <name /> </author> <link rel="edit" title="Person" href="People(1)" /> <category term="DeadSimpleServer.Models.Person" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /> <content type="application/xml"> <m:properties> <d:ID m:type="Edm.Int32">1</d:ID> <d:Name>George Washington</d:Name> </m:properties> </content> </entry> <entry> ... </entry> </feed> Let's recap what we've done so far. But enough with services and XML - let's get this into our Windows Phone client application. Creating the DataServiceContext for the Client Use the latest DataSvcUtil.exe from http://odata.codeplex.com. As of today, that's in this download: http://odata.codeplex.com/releases/view/54698 You need to run it with a few options: /uri - This will point to the service URI. In this case, it's http://localhost:59342/PersonTestDataService.svc  Pick up the port number from your running server (e.g., the server formerly known as Cassini). /out - This is the DataServiceContext class that will be generated. You can name it whatever you'd like. /Version - should be set to 2.0 /DataServiceCollection - Include this flag to generate collections derived from the DataServiceCollection base, which brings in all the ObservableCollection goodness that handles your INotifyPropertyChanged events for you. Here's the console session from when we ran it: <ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding}" SelectionChanged="MainListBox_SelectionChanged"> Next, to keep things simple, change the Binding on the two TextBlocks within the DataTemplate to Name and ID, <ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding}" SelectionChanged="MainListBox_SelectionChanged"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Margin="0,0,0,17" Width="432"> <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" /> <TextBlock Text="{Binding ID}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Getting The Context In the code-behind you’ll first declare a member variable to hold the context from the Entity Framework. This is named using convention over configuration. The db type is Person and the context is of type PersonContext, You initialize it by providing the URI, in this case using the URL obtained from the Cassini web server, PersonContext context = new PersonContext( new Uri( "http://localhost:49786/PersonTestDataService.svc/" ) ); Create a second member variable of type DataServiceCollection<Person> but do not initialize it, DataServiceCollection<Person> people; In the constructor you’ll initialize the DataServiceCollection using the PersonContext, public MainPage() { InitializeComponent(); people = new DataServiceCollection<Person>( context ); Finally, you’ll load the people collection using the LoadAsync method, passing in the fully specified URI for the People collection in the web service, people.LoadAsync( new Uri( "http://localhost:49786/PersonTestDataService.svc/People" ) ); Note that this method runs asynchronously and when it is finished the people  collection is already populated. Thus, since we didn’t need or want to override any of the behavior we don’t implement the LoadCompleted. You can use the LoadCompleted event if you need to do any other UI updates, but you don't need to. The final code is as shown below: using System; using System.Data.Services.Client; using System.Windows; using System.Windows.Controls; using DeadSimpleServer.Models; using Microsoft.Phone.Controls; namespace WindowsPhoneODataTest { public partial class MainPage : PhoneApplicationPage { PersonContext context = new PersonContext( new Uri( "http://localhost:49786/PersonTestDataService.svc/" ) ); DataServiceCollection<Person> people; // Constructor public MainPage() { InitializeComponent(); // Set the data context of the listbox control to the sample data // DataContext = App.ViewModel; people = new DataServiceCollection<Person>( context ); people.LoadAsync( new Uri( "http://localhost:49786/PersonTestDataService.svc/People" ) ); DataContext = people; this.Loaded += new RoutedEventHandler( MainPage_Loaded ); } // Handle selection changed on ListBox private void MainListBox_SelectionChanged( object sender, SelectionChangedEventArgs e ) { // If selected index is -1 (no selection) do nothing if ( MainListBox.SelectedIndex == -1 ) return; // Navigate to the new page NavigationService.Navigate( new Uri( "/DetailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative ) ); // Reset selected index to -1 (no selection) MainListBox.SelectedIndex = -1; } // Load data for the ViewModel Items private void MainPage_Loaded( object sender, RoutedEventArgs e ) { if ( !App.ViewModel.IsDataLoaded ) { App.ViewModel.LoadData(); } } } } With people populated we can set it as the DataContext and run the application; you’ll find that the Name and ID are displayed in the list on the Mainpage. Here's how the pieces in the client fit together: Complete source code available here

    Read the article

  • WPF Data Binding won't work

    - by Tokk
    Hey, I have got an UserControll with a DependencyProperty called "Risikobewertung" whitch has the own Datatype "RisikoBewertung"(Datatype created by LINQ). So in my Controll I try to bind the Fields of RisikoBewertung to the TextBoxes on the Controll, but It won't work. I hope you can help me, and tell me why ;) Code: UserControl.xaml: <UserControl x:Class="Cis.Modules.RiskManagement.Views.Controls.RisikoBewertungEditor" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:gridtools="clr-namespace:TmgUnity.Common.Presentation.Controls.DataGridTools;assembly=TmgUnity.Common.Presentation" xmlns:converter="clr-namespace:Cis.Modules.RiskManagement.Views.Converter" xmlns:tmg="clr-namespace:TmgUnity.Common.Presentation.Controls.FilterDataGrid;assembly=TmgUnity.Common.Presentation" xmlns:validators="clr-namespace:TmgUnity.Common.Presentation.ValidationRules;assembly=TmgUnity.Common.Presentation" xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" xmlns:risikoControls="clr-namespace:Cis.Modules.RiskManagement.Views.Controls"> <UserControl.Resources> <converter:CountToArrowConverter x:Key="CountConverter" /> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Name="Veränderung"/> <ColumnDefinition Name="Volumen" /> <ColumnDefinition Name="Schadenshöhe" /> <ColumnDefinition Name="SchadensOrte" /> <ColumnDefinition Name="Wahrscheinlichkeit" /> <ColumnDefinition Name="Kategorie" /> <ColumnDefinition Name="Handlungsbedarf" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="20" /> <RowDefinition /> </Grid.RowDefinitions> <Image Source="{Binding Path=Entwicklung, Converter={StaticResource CountConverter}, UpdateSourceTrigger=PropertyChanged}" Grid.RowSpan="2" Grid.Row="0" Width="68" Height="68" Grid.Column="0" /> <TextBox Grid.Column="1" Grid.Row="0" Text="Volumen" /> <TextBox Grid.Column="1" Grid.Row="1"> <TextBox.Text> <Binding Path="Volumen" UpdateSourceTrigger="PropertyChanged" /> </TextBox.Text> </TextBox> <TextBox Grid.Column="2" Grid.Row="0" Text="Schadenshöhe" /> <TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Schadenshöhe, UpdateSourceTrigger=PropertyChanged}" /> <StackPanel Grid.Column="3" Grid.RowSpan="2" Grid.Row="0" Orientation="Horizontal"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="20" /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBox Text ="Politik" Grid.Row="0" Grid.Column="0"/> <CheckBox Name="Politik" Grid.Row="1" Grid.Column="0" IsChecked="{Binding Path=Politik, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" /> <TextBox Text ="Vermögen" Grid.Row="0" Grid.Column="1" /> <CheckBox Name="Vermögen" Grid.Row="1" Grid.Column="1" IsChecked="{Binding Path=Vermögen, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" /> <TextBox Text ="Vertrauen" Grid.Row="0" Grid.Column="2" /> <CheckBox Name="Vertrauen" Grid.Row="1" Grid.Column="2" IsChecked="{Binding Path=Vertrauen, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" /> </Grid> </StackPanel> <TextBox Grid.Column="4" Grid.Row="0" Text="Wahrscheinlichkeit" /> <TextBox Grid.Column="4" Grid.Row="1" Text="{Binding Path=Wahrscheinlichkeit, UpdateSourceTrigger=PropertyChanged}"/> <risikoControls:RiskTrafficLightControl Grid.Column="5" Grid.Row="0" Grid.RowSpan="2" RiskValue="{Binding Path=Kategorie, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> <StackPanel Grid.Column="6" Grid.RowSpan="2" Grid.Row="0" Orientation="Vertical"> <TextBox Text="Handlungsbedarf" /> <CheckBox VerticalAlignment="Center" HorizontalAlignment="Center" IsChecked="{Binding Path=Handlungsbedarf, UpdateSourceTrigger=PropertyChanged}" /> </StackPanel> </Grid> The CodeBehind: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.ComponentModel; using Cis.Modules.RiskManagement.Data; using Cis.Modules.RiskManagement.Views.Models; namespace Cis.Modules.RiskManagement.Views.Controls { /// <summary> /// Interaktionslogik für RisikoBewertungEditor.xaml /// </summary> public partial class RisikoBewertungEditor : UserControl, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static readonly DependencyProperty RisikoBewertungProperty = DependencyProperty.Register("RisikoBewertung", typeof(RisikoBewertung), typeof(RisikoBewertungEditor), new PropertyMetadata(null, new PropertyChangedCallback(RisikoBewertungChanged))); // public static readonly DependencyProperty Readonly = DependencyProperty.Register("EditorReadonly", typeof(Boolean), typeof(RisikoBewertungEditor), new PropertyMetadata(null, new PropertyChangedCallback(ReadonlyChanged))); private static void RisikoBewertungChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs arguments) { var bewertungEditor = dependencyObject as RisikoBewertungEditor; bewertungEditor.RisikoBewertung = arguments.NewValue as RisikoBewertung; } /* private static void ReadonlyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs arguments) { } */ public RisikoBewertung RisikoBewertung { get { return GetValue(RisikoBewertungProperty) as RisikoBewertung; } set { SetValue(RisikoBewertungProperty, value); if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("RisikoBewertung")); } } } /* public Boolean EditorReadonly { get; set; } */ public void mebosho(object sender, RoutedEventArgs e) { MessageBox.Show(RisikoBewertung.LfdNr.ToString()); } public RisikoBewertungEditor() { InitializeComponent(); RisikoBewertung = new RisikoBewertung(); this.DataContext = (GetValue(RisikoBewertungProperty) as RisikoBewertung); } } } and a little example of it's usage: <tmg:FilterDataGrid Grid.Row="0" AutoGenerateColumns="False" ItemsSource="{Binding TodoListe}" IsReadOnly="False" x:Name="TodoListeDataGrid" CanUserAddRows="False" SelectionUnit="FullRow" SelectedValuePath="." SelectedValue="{Binding CurrentTodoItem}" gridtools:DataGridStyle.SelectAllButtonTemplate="{DynamicResource CisSelectAllButtonTemplate}" CanUserResizeColumns="True" MinHeight="80" SelectionChanged="SelectionChanged" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" diagnostics:PresentationTraceSources.TraceLevel="High" > <tmg:FilterDataGrid.RowDetailsTemplate> <DataTemplate> <risikoControls:RisikoBewertungEditor x:Name="BewertungEditor" RisikoBewertung="{Binding ElementName=TodoListeDataGrid, Path=SelectedValue}" diagnostics:PresentationTraceSources.TraceLevel="High"> </risikoControls:RisikoBewertungEditor> </DataTemplate> </tmg:FilterDataGrid.RowDetailsTemplate> <tmg:FilterDataGrid.Columns> <toolkit:DataGridTextColumn Binding="{Binding Path=LfdNr}" Header="LfdNr" /> </tmg:FilterDataGrid.Columns> </tmg:FilterDataGrid>

    Read the article

  • Databinding, using formulas for unusual binding possible?

    - by Rattenmann
    Edit: added Info for WPF being used I am trying to bind a list of custom objects to a DataGrid. Straight binding seems easy enough, but i need to specify some complex formulas for some extra fields that do not directly show up in my class. Also i want to be able to EDIT the data in the Grid and get updates on related fields. Let me show you an example, because it is really hard to explain. I will simplify it to rooms with items. Each item can be red and blue. My Class looks like this: public class room { public string strRoomName { set; get; } public string strItemname { set; get; } public int intRedItem { set; get; } public int intBlueItem { set; get; } } Now if i use dataTable.ItemSource = myList; i get something like this: nr. | room | name | red | blue 1. living room, ball, 2, 1 2. sleeping room, bunny, 4, 1 3. living room, chair, 3, 2 4. kitchen, ball, 4, 7 5. garage, chair, 1, 4 Now for the complex part i need help with. I want every item to be the same number, red and blue. And because this does not hold true i want to see the "inbalance" per room AND globally like this: nr. | room | name | red | blue | missing | global red | global blue | global missing 1. living room, ball, 2, 1, 1 blue, 6, 7, 1 red 2. sleeping room, bunny, 4, 1, 3 blue, 4, 1, 3 blue 3. living room, chair, 3, 2, 1 blue, 4, 6, 2 red 4. kitchen, ball, 4, 7, 3 red, 6, 7, 1 red 5. garage, chair, 1, 4, 3 red, 4, 6, 2 red As you can see this smeels like excel formulas, i am unsure how to handle this in c# code however. You can also see i need to use data in the same row, but also get data from other rows that match one propertiy (the items name). Also if i change the blue value=1 in line 1 to value=2, i want line 1 to read like this: 1. living room, ball, 2, 2, even, 6, 8, 2 red and of corse line 4 needs to change to: 4. kitchen, ball, 4, 7, 3 red, 6, 8, 2 red As i said, this smells like excel, that's why i am really upset about myself not finding an easy solution. Surely enough c# offers some way to handle this stuff, right? Disclaimer: It is totally possible that i need a complete differend approach, pointing that out ot me is perfectly fine. Be it other ways to handle this, or a better way to structure my class. I am ok with every way to handle this as it is for learning purposes. I am simply doing programms for fun next to my college and just so happen to hit these kinda things that bug me out because i don't find a clean solution. And then i neglect my studies because i want to solve my (unreleated to studys,...) issue. Just can't stand having unsolved coding stuff around, don't judge me! ;-) And big thanks in advance if you have gotten this far in my post. It sure must be confusing with all those reds and blues. Edit: After reading trough your answers and testing my skills to implement your hints, i now have the following code as my class: public class RoomList : ObservableCollection<room> { public RoomList() : base() { Add(new room() { strRoomName = "living room", strItemname = "ball", intRedItem = 2, intBlueItem = 1 }); Add(new room() { strRoomName = "sleeping room", strItemname = "bunny", intRedItem = 4, intBlueItem = 1 }); Add(new room() { strRoomName = "living room", strItemname = "chair", intRedItem = 3, intBlueItem = 2 }); Add(new room() { strRoomName = "kitchen", strItemname = "ball", intRedItem = 4, intBlueItem = 7 }); Add(new room() { strRoomName = "garage", strItemname = "chair", intRedItem = 1, intBlueItem = 4 }); } } //rooms public class room : INotifyPropertyChanged { public string strRoomName { set; get; } public string strItemname { set; get; } public int intRedItem { get { return intRedItem; } set { intRedItem = value; NotifyPropertyChanged("intRedItem", "strMissing"); } } public int intBlueItem { get { return intBlueItem; } set { intBlueItem = value; NotifyPropertyChanged("intBlueItem", "strMissing"); } } public string strMissing { get { int missingCount = intRedItem - intBlueItem; return missingCount == 0 ? "Even" : missingCount.ToString(); } } public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(params string[] propertyNames) { if (PropertyChanged != null) { foreach (string propertyName in propertyNames) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } } I got the "missing" field working right away, thanks alot for that tip. It really was as easy as i imagined and will be of great use for future projects. Still two (three maybe....) things i am missing tho. The above code terminates with a "System.StackOverflowException" in the setter of intRedItem and intBlueItem. I fail to see the error, that could be due to being 4:30am here, or my lack of understanding. Second issue: I followed the link to ObservableCollections as you can see from my code above. Yet i am unsure how to actually use that collection. Putting it as DataContent like suggested on that page shows a missing ressource. Adding it as a ressource like listed there crashes my VSExpress designer and leads to the programm not starting. So for now i am still using my old approach of a list like this: listRooms.Add(new room() { strRoomName = "living room", strItemname = "ball", intRedItem = 2, intBlueItem = 1 }); listRooms.Add(new room() { strRoomName = "sleeping room", strItemname = "bunny", intRedItem = 4, intBlueItem = 1 }); listRooms.Add(new room() { strRoomName = "living room", strItemname = "chair", intRedItem = 3, intBlueItem = 2 }); listRooms.Add(new room() { strRoomName = "kitchen", strItemname = "ball", intRedItem = 4, intBlueItem = 7 }); listRooms.Add(new room() { strRoomName = "garage", strItemname = "chair", intRedItem = 1, intBlueItem = 4 }); datagridRooms.ItemsSource = listRooms; And lastly: When testing before adding the notifyevents i tried to implement a proterty that looped trough the other objects, without any luck. The "missingItem" property worked so easy, yet it only tries to access "it's own" properties kind of. I need to access other objects, like "all objects that have the same room value". The idea behind this is that i am trying to calculate a value from other objects without even having those objects yet, at least in my logic. Where is the flaw in my thinking? Those 5 objects are added and created (?) one after another. So if the first tries to set it's "all red balls in my room AND all other rooms" value,.. how could it know about the balls in the kitchen, that get added as 4th object? So far so good tho, got on the right track i think. Just need some sleep first.

    Read the article

  • Building applications with WPF, MVVM and Prism(aka CAG)

    - by skjagini
    In this article I am going to walk through an application using WPF and Prism (aka composite application guidance, CAG) which simulates engaging a taxi (cab).  The rules are simple, the app would have3 screens A login screen to authenticate the user An information screen. A screen to engage the cab and roam around and calculating the total fare Metered Rate of Fare The meter is required to be engaged when a cab is occupied by anyone $3.00 upon entry $0.35 for each additional unit The unit fare is: one-fifth of a mile, when the cab is traveling at 6 miles an hour or more; or 60 seconds when not in motion or traveling at less than 12 miles per hour. Night surcharge of $.50 after 8:00 PM & before 6:00 AM Peak hour Weekday Surcharge of $1.00 Monday - Friday after 4:00 PM & before 8:00 PM New York State Tax Surcharge of $.50 per ride. Example: Friday (2010-10-08) 5:30pm Start at Lexington Ave & E 57th St End at Irving Pl & E 15th St Start = $3.00 Travels 2 miles at less than 6 mph for 15 minutes = $3.50 Travels at more than 12 mph for 5 minutes = $1.75 Peak hour Weekday Surcharge = $1.00 (ride started at 5:30 pm) New York State Tax Surcharge = $0.50 Before we dive into the app, I would like to give brief description about the framework.  If you want to jump on to the source code, scroll all the way to the end of the post. MVVM MVVM pattern is in no way related to the usage of PRISM in your application and should be considered if you are using WPF irrespective of PRISM or not. Lets say you are not familiar with MVVM, your typical UI would involve adding some UI controls like text boxes, a button, double clicking on the button,  generating event handler, calling a method from business layer and updating the user interface, it works most of the time for developing small scale applications. The problem with this approach is that there is some amount of code specific to business logic wrapped in UI specific code which is hard to unit test it, mock it and MVVM helps to solve the exact problem. MVVM stands for Model(M) – View(V) – ViewModel(VM),  based on the interactions with in the three parties it should be called VVMM,  MVVM sounds more like MVC (Model-View-Controller) so the name. Why it should be called VVMM: View – View Model - Model WPF allows to create user interfaces using XAML and MVVM takes it to the next level by allowing complete separation of user interface and business logic. In WPF each view will have a property, DataContext when set to an instance of a class (which happens to be your view model) provides the data the view is interested in, i.e., view interacts with view model and at the same time view model interacts with view through DataContext. Sujith, if view and view model are interacting directly with each other how does MVVM is helping me separation of concerns? Well, the catch is DataContext is of type Object, since it is of type object view doesn’t know exact type of view model allowing views and views models to be loosely coupled. View models aggregate data from models (data access layer, services, etc) and make it available for views through properties, methods etc, i.e., View Models interact with Models. PRISM Prism is provided by Microsoft Patterns and Practices team and it can be downloaded from codeplex for source code,  samples and documentation on msdn.  The name composite implies, to compose user interface from different modules (views) without direct dependencies on each other, again allowing  loosely coupled development. Well Sujith, I can already do that with user controls, why shall I learn another framework?  That’s correct, you can decouple using user controls, but you still have to manage some amount of coupling, like how to do you communicate between the controls, how do you subscribe/unsubscribe, loading/unloading views dynamically. Prism is not a replacement for user controls, provides the following features which greatly help in designing the composite applications. Dependency Injection (DI)/ Inversion of Control (IoC) Modules Regions Event Aggregator  Commands Simply put, MVVM helps building a single view and Prism helps building an application using the views There are other open source alternatives to Prism, like MVVMLight, Cinch, take a look at them as well. Lets dig into the source code.  1. Solution The solution is made of the following projects Framework: Holds the common functionality in building applications using WPF and Prism TaxiClient: Start up project, boot strapping and app styling TaxiCommon: Helps with the business logic TaxiModules: Holds the meat of the application with views and view models TaxiTests: To test the application 2. DI / IoC Dependency Injection (DI) as the name implies refers to injecting dependencies and Inversion of Control (IoC) means the calling code has no direct control on the dependencies, opposite of normal way of programming where dependencies are passed by caller, i.e inversion; aside from some differences in terminology the concept is same in both the cases. The idea behind DI/IoC pattern is to reduce the amount of direct coupling between different components of the application, the higher the dependency the more tightly coupled the application resulting in code which is hard to modify, unit test and mock.  Initializing Dependency Injection through BootStrapper TaxiClient is the starting project of the solution and App (App.xaml)  is the starting class that gets called when you run the application. From the App’s OnStartup method we will invoke BootStrapper.   namespace TaxiClient { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e);   (new BootStrapper()).Run(); } } } BootStrapper is your contact point for initializing the application including dependency injection, creating Shell and other frameworks. We are going to use Unity for DI and there are lot of open source DI frameworks like Spring.Net, StructureMap etc with different feature set  and you can choose a framework based on your preferences. Note that Prism comes with in built support for Unity, for example we are deriving from UnityBootStrapper in our case and for any other DI framework you have to extend the Prism appropriately   namespace TaxiClient { public class BootStrapper: UnityBootstrapper { protected override IModuleCatalog CreateModuleCatalog() { return new ConfigurationModuleCatalog(); } protected override DependencyObject CreateShell() { Framework.FrameworkBootStrapper.Run(Container, Application.Current.Dispatcher);   Shell shell = new Shell(); shell.ResizeMode = ResizeMode.NoResize; shell.Show();   return shell; } } } Lets take a look into  FrameworkBootStrapper to check out how to register with unity container. namespace Framework { public class FrameworkBootStrapper { public static void Run(IUnityContainer container, Dispatcher dispatcher) { UIDispatcher uiDispatcher = new UIDispatcher(dispatcher); container.RegisterInstance<IDispatcherService>(uiDispatcher);   container.RegisterType<IInjectSingleViewService, InjectSingleViewService>( new ContainerControlledLifetimeManager());   . . . } } } In the above code we are registering two components with unity container. You shall observe that we are following two different approaches, RegisterInstance and RegisterType.  With RegisterInstance we are registering an existing instance and the same instance will be returned for every request made for IDispatcherService   and with RegisterType we are requesting unity container to create an instance for us when required, i.e., when I request for an instance for IInjectSingleViewService, unity will create/return an instance of InjectSingleViewService class and with RegisterType we can configure the life time of the instance being created. With ContaienrControllerLifetimeManager, the unity container caches the instance and reuses for any subsequent requests, without recreating a new instance. Lets take a look into FareViewModel.cs and it’s constructor. The constructor takes one parameter IEventAggregator and if you try to find all references in your solution for IEventAggregator, you will not find a single location where an instance of EventAggregator is passed directly to the constructor. The compiler still finds an instance and works fine because Prism is already configured when used with Unity container to return an instance of EventAggregator when requested for IEventAggregator and in this particular case it is called constructor injection. public class FareViewModel:ObservableBase, IDataErrorInfo { ... private IEventAggregator _eventAggregator;   public FareViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; InitializePropertyNames(); InitializeModel(); PropertyChanged += OnPropertyChanged; } ... 3. Shell Shells are very similar in operation to Master Pages in asp.net or MDI in Windows Forms. And shells contain regions which display the views, you can have as many regions as you wish in a given view. You can also nest regions. i.e, one region can load a view which in itself may contain other regions. We have to create a shell at the start of the application and are doing it by overriding CreateShell method from BootStrapper From the following Shell.xaml you shall notice that we have two content controls with Region names as ‘MenuRegion’ and ‘MainRegion’.  The idea here is that you can inject any user controls into the regions dynamically, i.e., a Menu User Control for MenuRegion and based on the user action you can load appropriate view into MainRegion.    <Window x:Class="TaxiClient.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Regions="clr-namespace:Microsoft.Practices.Prism.Regions;assembly=Microsoft.Practices.Prism" Title="Taxi" Height="370" Width="800"> <Grid Margin="2"> <ContentControl Regions:RegionManager.RegionName="MenuRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />   <ContentControl Grid.Row="1" Regions:RegionManager.RegionName="MainRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" /> <!--<Border Grid.ColumnSpan="2" BorderThickness="2" CornerRadius="3" BorderBrush="LightBlue" />-->   </Grid> </Window> 4. Modules Prism provides the ability to build composite applications and modules play an important role in it. For example if you are building a Mortgage Loan Processor application with 3 components, i.e. customer’s credit history,  existing mortgages, new home/loan information; and consider that the customer’s credit history component involves gathering data about his/her address, background information, job details etc. The idea here using Prism modules is to separate the implementation of these 3 components into their own visual studio projects allowing to build components with no dependency on each other and independently. If we need to add another component to the application, the component can be developed by in house team or some other team in the organization by starting with a new Visual Studio project and adding to the solution at the run time with very little knowledge about the application. Prism modules are defined by implementing the IModule interface and each visual studio project to be considered as a module should implement the IModule interface.  From the BootStrapper.cs you shall observe that we are overriding the method by returning a ConfiguratingModuleCatalog which returns the modules that are registered for the application using the app.config file  and you can also add module using code. Lets take a look into configuration file.   <?xml version="1.0"?> <configuration> <configSections> <section name="modules" type="Microsoft.Practices.Prism.Modularity.ModulesConfigurationSection, Microsoft.Practices.Prism"/> </configSections> <modules> <module assemblyFile="TaxiModules.dll" moduleType="TaxiModules.ModuleInitializer, TaxiModules" moduleName="TaxiModules"/> </modules> </configuration> Here we are adding TaxiModules project to our solution and TaxiModules.ModuleInitializer implements IModule interface   5. Module Mapper With Prism modules you can dynamically add or remove modules from the regions, apart from that Prism also provides API to control adding/removing the views from a region within the same module. Taxi Information Screen: Engage the Taxi Screen: The sample application has two screens, ‘Taxi Information’ and ‘Engage the Taxi’ and they both reside in same module, TaxiModules. ‘Engage the Taxi’ is again made of two user controls, FareView on the left and TotalView on the right. We have created a Shell with two regions, MenuRegion and MainRegion with menu loaded into MenuRegion. We can create a wrapper user control called EngageTheTaxi made of FareView and TotalView and load either TaxiInfo or EngageTheTaxi into MainRegion based on the user action. Though it will work it tightly binds the user controls and for every combination of user controls, we need to create a dummy wrapper control to contain them. Instead we can apply the principles we learned so far from Shell/regions and introduce another template (LeftAndRightRegionView.xaml) made of two regions Region1 (left) and Region2 (right) and load  FareView and TotalView dynamically.  To help with loading of the views dynamically I have introduce an helper an interface, IInjectSingleViewService,  idea suggested by Mike Taulty, a must read blog for .Net developers. using System; using System.Collections.Generic; using System.ComponentModel;   namespace Framework.PresentationUtility.Navigation {   public interface IInjectSingleViewService : INotifyPropertyChanged { IEnumerable<CommandViewDefinition> Commands { get; } IEnumerable<ModuleViewDefinition> Modules { get; }   void RegisterViewForRegion(string commandName, string viewName, string regionName, Type viewType); void ClearViewFromRegion(string viewName, string regionName); void RegisterModule(string moduleName, IList<ModuleMapper> moduleMappers); } } The Interface declares three methods to work with views: RegisterViewForRegion: Registers a view with a particular region. You can register multiple views and their regions under one command.  When this particular command is invoked all the views registered under it will be loaded into their regions. ClearViewFromRegion: To unload a specific view from a region. RegisterModule: The idea is when a command is invoked you can load the UI with set of controls in their default position and based on the user interaction, you can load different contols in to different regions on the fly.  And it is supported ModuleViewDefinition and ModuleMappers as shown below. namespace Framework.PresentationUtility.Navigation { public class ModuleViewDefinition { public string ModuleName { get; set; } public IList<ModuleMapper> ModuleMappers; public ICommand Command { get; set; } }   public class ModuleMapper { public string ViewName { get; set; } public string RegionName { get; set; } public Type ViewType { get; set; } } } 6. Event Aggregator Prism event aggregator enables messaging between components as in Observable pattern, Notifier notifies the Observer which receives notification it is interested in. When it comes to Observable pattern, Observer has to unsubscribes for notifications when it no longer interested in notifications, which allows the Notifier to remove the Observer’s reference from it’s local cache. Though .Net has managed garbage collection it cannot remove inactive the instances referenced by an active instance resulting in memory leak, keeping the Observers in memory as long as Notifier stays in memory.  Developers have to be very careful to unsubscribe when necessary and it often gets overlooked, to overcome these problems Prism Event Aggregator uses weak references to cache the reference (Observer in this case)  and releases the reference (memory) once the instance goes out of scope. Using event aggregator is very simple, declare a generic type of CompositePresenationEvent by inheriting from it. using Microsoft.Practices.Prism.Events; using TaxiCommon.BAO;   namespace TaxiCommon.CompositeEvents { public class TaxiOnMoveEvent:CompositePresentationEvent<TaxiOnMove> { } }   TaxiOnMove.cs includes the properties which we want to exchange between the parties, FareView and TotalView. using System;   namespace TaxiCommon.BAO { public class TaxiOnMove { public TimeSpan MinutesAtTweleveMPH { get; set; } public double MilesAtSixMPH { get; set; } } }   Lets take a look into FareViewodel (Notifier) and how it raises the event.  Here we are raising the event by getting the event through GetEvent<..>() and publishing it with the payload private void OnAddMinutes(object obj) { TaxiOnMove payload = new TaxiOnMove(); if(MilesAtSixMPH != null) payload.MilesAtSixMPH = MilesAtSixMPH.Value; if(MinutesAtTweleveMPH != null) payload.MinutesAtTweleveMPH = new TimeSpan(0,0,MinutesAtTweleveMPH.Value,0);   _eventAggregator.GetEvent<TaxiOnMoveEvent>().Publish(payload); ResetMinutesAndMiles(); } And TotalViewModel(Observer) subscribes to notifications by getting the event through GetEvent<..>() namespace TaxiModules.ViewModels { public class TotalViewModel:ObservableBase { .... private IEventAggregator _eventAggregator;   public TotalViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; ... }   private void SubscribeToEvents() { _eventAggregator.GetEvent<TaxiStartedEvent>() .Subscribe(OnTaxiStarted, ThreadOption.UIThread,false,(filter) => true); _eventAggregator.GetEvent<TaxiOnMoveEvent>() .Subscribe(OnTaxiMove, ThreadOption.UIThread, false, (filter) => true); _eventAggregator.GetEvent<TaxiResetEvent>() .Subscribe(OnTaxiReset, ThreadOption.UIThread, false, (filter) => true); }   ... private void OnTaxiMove(TaxiOnMove taxiOnMove) { OnMoveFare fare = new OnMoveFare(taxiOnMove); Fares.Add(fare); SetTotalFare(new []{fare}); }   .... 7. MVVM through example In this section we are going to look into MVVM implementation through example.  I have all the modules declared in a single project, TaxiModules, again it is not necessary to have them into one project. Once the user logs into the application, will be greeted with the ‘Engage the Taxi’ screen which is made of two user controls, FareView.xaml and TotalView.Xaml. As you can see from the solution explorer, each of them have their own code behind files and  ViewModel classes, FareViewMode.cs, TotalViewModel.cs Lets take a look in to the FareView and how it interacts with FareViewModel using MVVM implementation. FareView.xaml acts as a view and FareViewMode.cs is it’s view model. The FareView code behind class   namespace TaxiModules.Views { /// <summary> /// Interaction logic for FareView.xaml /// </summary> public partial class FareView : UserControl { public FareView(FareViewModel viewModel) { InitializeComponent(); this.Loaded += (s, e) => { this.DataContext = viewModel; }; } } } The FareView is bound to FareViewModel through the data context  and you shall observe that DataContext is of type Object, i.e. the FareView doesn’t really know the type of ViewModel (FareViewModel). This helps separation of View and ViewModel as View and ViewModel are independent of each other, you can bind FareView to FareViewModel2 as well and the application compiles just fine. Lets take a look into FareView xaml file  <UserControl x:Class="TaxiModules.Views.FareView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" xmlns:Commands="clr-namespace:Microsoft.Practices.Prism.Commands;assembly=Microsoft.Practices.Prism"> <Grid Margin="10" > ....   <Border Style="{DynamicResource innerBorder}" Grid.Row="0" Grid.Column="0" Grid.RowSpan="11" Grid.ColumnSpan="2" Panel.ZIndex="1"/>   <Label Grid.Row="0" Content="Engage the Taxi" Style="{DynamicResource innerHeader}"/> <Label Grid.Row="1" Content="Select the State"/> <ComboBox Grid.Row="1" Grid.Column="1" ItemsSource="{Binding States}" Height="auto"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </ComboBox.ItemTemplate> <ComboBox.SelectedItem> <Binding Path="SelectedState" Mode="TwoWay"/> </ComboBox.SelectedItem> </ComboBox> <Label Grid.Row="2" Content="Select the Date of Entry"/> <Toolkit:DatePicker Grid.Row="2" Grid.Column="1" SelectedDate="{Binding DateOfEntry, ValidatesOnDataErrors=true}" /> <Label Grid.Row="3" Content="Enter time 24hr format"/> <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding TimeOfEntry, TargetNullValue=''}"/> <Button Grid.Row="4" Grid.Column="1" Content="Start the Meter" Commands:Click.Command="{Binding StartMeterCommand}" />   <Label Grid.Row="5" Content="Run the Taxi" Style="{DynamicResource innerHeader}"/> <Label Grid.Row="6" Content="Number of Miles &lt;@6mph"/> <TextBox Grid.Row="6" Grid.Column="1" Text="{Binding MilesAtSixMPH, TargetNullValue='', ValidatesOnDataErrors=true}"/> <Label Grid.Row="7" Content="Number of Minutes @12mph"/> <TextBox Grid.Row="7" Grid.Column="1" Text="{Binding MinutesAtTweleveMPH, TargetNullValue=''}"/> <Button Grid.Row="8" Grid.Column="1" Content="Add Minutes and Miles " Commands:Click.Command="{Binding AddMinutesCommand}"/> <Label Grid.Row="9" Content="Other Operations" Style="{DynamicResource innerHeader}"/> <Button Grid.Row="10" Grid.Column="1" Content="Reset the Meter" Commands:Click.Command="{Binding ResetCommand}"/>   </Grid> </UserControl> The highlighted code from the above code shows data binding, for example ComboBox which displays list of states has it’s ItemsSource bound to States property, with DataTemplate bound to Name and SelectedItem  to SelectedState. You might be wondering what are all these properties and how it is able to bind to them.  The answer lies in data context, i.e., when you bound a control, WPF looks for data context on the root object (Grid in this case) and if it can’t find data context it will look into root’s root, i.e. FareView UserControl and it is bound to FareViewModel.  Each of those properties have be declared on the ViewModel for the View to bind correctly. To put simply, View is bound to ViewModel through data context of type object and every control that is bound on the View actually binds to the public property on the ViewModel. Lets look into the ViewModel code (the following code is not an exact copy of FareViewMode.cs, pasted relevant code for this section)   namespace TaxiModules.ViewModels { public class FareViewModel:ObservableBase, IDataErrorInfo { public List<USState> States { get { return USStates.StateList; } }   public USState SelectedState { get { return _selectedState; } set { _selectedState = value; RaisePropertyChanged(_selectedStatePropertyName); } }   public DateTime? DateOfEntry { get { return _dateOfEntry; } set { _dateOfEntry = value; RaisePropertyChanged(_dateOfEntryPropertyName); } }   public TimeSpan? TimeOfEntry { get { return _timeOfEntry; } set { _timeOfEntry = value; RaisePropertyChanged(_timeOfEntryPropertyName); } }   public double? MilesAtSixMPH { get { return _milesAtSixMPH; } set { _milesAtSixMPH = value; RaisePropertyChanged(_distanceAtSixMPHPropertyName); } }   public int? MinutesAtTweleveMPH { get { return _minutesAtTweleveMPH; } set { _minutesAtTweleveMPH = value; RaisePropertyChanged(_minutesAtTweleveMPHPropertyName); } }   public ICommand StartMeterCommand { get { if(_startMeterCommand == null) { _startMeterCommand = new DelegateCommand<object>(OnStartMeter, CanStartMeter); } return _startMeterCommand; } }   public ICommand AddMinutesCommand { get { if(_addMinutesCommand == null) { _addMinutesCommand = new DelegateCommand<object>(OnAddMinutes, CanAddMinutes); } return _addMinutesCommand; } }   public ICommand ResetCommand { get { if(_resetCommand == null) { _resetCommand = new DelegateCommand<object>(OnResetCommand); } return _resetCommand; } }   } private void OnStartMeter(object obj) { _eventAggregator.GetEvent<TaxiStartedEvent>().Publish( new TaxiStarted() { EngagedOn = DateOfEntry.Value.Date + TimeOfEntry.Value, EngagedState = SelectedState.Value });   _isMeterStarted = true; OnPropertyChanged(this,null); } And views communicate user actions like button clicks, tree view item selections, etc using commands. When user clicks on ‘Start the Meter’ button it invokes the method StartMeterCommand, which calls the method OnStartMeter which publishes the event to TotalViewModel using event aggregator  and TaxiStartedEvent. namespace TaxiModules.ViewModels { public class TotalViewModel:ObservableBase { ... private IEventAggregator _eventAggregator;   public TotalViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator;   InitializePropertyNames(); InitializeModel(); SubscribeToEvents(); }   public decimal? TotalFare { get { return _totalFare; } set { _totalFare = value; RaisePropertyChanged(_totalFarePropertyName); } } .... private void SubscribeToEvents() { _eventAggregator.GetEvent<TaxiStartedEvent>().Subscribe(OnTaxiStarted, ThreadOption.UIThread,false,(filter) => true); _eventAggregator.GetEvent<TaxiOnMoveEvent>().Subscribe(OnTaxiMove, ThreadOption.UIThread, false, (filter) => true); _eventAggregator.GetEvent<TaxiResetEvent>().Subscribe(OnTaxiReset, ThreadOption.UIThread, false, (filter) => true); }   private void OnTaxiStarted(TaxiStarted taxiStarted) { Fares.Add(new EntryFare()); Fares.Add(new StateTaxFare(taxiStarted)); Fares.Add(new NightSurchargeFare(taxiStarted)); Fares.Add(new PeakHourWeekdayFare(taxiStarted));   SetTotalFare(Fares); }   private void SetTotalFare(IEnumerable<IFare> fares) { TotalFare = (_totalFare ?? 0) + TaxiFareHelper.GetTotalFare(fares); } ....   } }   TotalViewModel subscribes to events, TaxiStartedEvent and rest. When TaxiStartedEvent gets invoked it calls the OnTaxiStarted method which sets the total fare which includes entry fee, state tax, nightly surcharge, peak hour weekday fare.   Note that TotalViewModel derives from ObservableBase which implements the method RaisePropertyChanged which we are invoking in Set of TotalFare property, i.e, once we update the TotalFare property it raises an the event that  allows the TotalFare text box to fetch the new value through the data context. ViewModel is communicating with View through data context and it has no knowledge about View, helping in loose coupling of ViewModel and View.   I have attached the source code (.Net 4.0, Prism 4.0, VS 2010) , download and play with it and don’t forget to leave your comments.  

    Read the article

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