Search Results

Search found 63 results on 3 pages for 'viewmodelbase'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • MVVM Light V4 preview (BL0014) release notes

    - by Laurent Bugnion
    I just pushed to Codeplex an update to the MVVM Light source code. This is an early preview containing some of the features that I want to release later under the version 4. If you find these features useful for your project, please download the source code and build the assemblies. I will appreciate greatly any issue report. This version is labeled “V4.0.0.0/BL0014”. The “BL” string is an old habit that we used in my days at Siemens Building Technologies, called a “base level”. Somehow I like this way of incrementing the “base level” independently of any other consideration (such as alpha, beta, CTP, RTM etc) and continue to use it to tag my software versions. In Microsoft parlance, you could say that this is an early CTP of MVVM Light V4. Caveat The code is unit tested, but as we all know this does not mean that there are no bugs This code has not yet been used in production. Again, your help in testing this is greatly appreciated, so please report all bugs to me! What’s new? The following features have been implemented: Misc Various “maintenance work”. All WPF assemblies (that is .NET35 and .NET4) now allow partially trusted callers. It means that you can use them in am XBAP in partial trust mode. Testing Various test updates Added Windows Phone 7 unit tests Note: For Windows Phone 7, due to an issue in the unit test framework, not all tests can be executed. I had to isolate those tests for the moment. The error was reported to Microsoft. ViewModelBase The constructor is now public to allow serialization (especially useful on the phone to tombstone the state). ViewModelBase.MessengerInstance now returns Messenger.Default unless it is set explicitly. Previously, MessengerInstance was returning null, which was complicating the code. Two new ways to raise the PropertyChanged event have been added. See below for details. Messenger Updated the IMessenger interface with all public members from the Messenger class. Previously some members were missing. A new Unregister method is now available, allowing to unregister a recipient for a given token. RelayCommand RaiseCanExecuteChanged now acts the same in Windows Presentation Foundation than in Silverlight. In previous versions, I was relying on the CommandManager to raise the CanExecuteChanged event in WPF. However, it was found to be too unreliable, and a more direct way of raising the event was found preferable. See below for details. Raising the PropertyChanged event A very much requested update is now included: the ability to raise the PropertyChanged event in a viewmodel without using “magic strings”. Personally, I don’t see strings as a major issue, thanks to two features of the MVVM Light Toolkit: In the DEBUG configuration, every time that the RaisePropertyChanged method is called, the name of the property is checked against all existing properties of the viewmodel. Should the property name be misspelled (because of a typo or refactoring), an exception is thrown, notifying the developer that something is wrong. To avoid impacting the performance, this check is only made in DEBUG configuration, but that should be enough to warn the developers in case they miss a rename. The property name is defined as a public constant in the “mvvminpc” code snippet. This allows checking the property name from another class (for example if the PropertyChanged event is handled in the view). It also allows changing the property name in one place only. However, these two safeguards didn’t satisfy some of the users, who requested another way to raise the PropertyChanged event. In V4, you can now do the following: Using lambdas private int _myProperty; public int MyProperty { get { return _myProperty; } set { if (_myProperty == value) { return; } _myProperty = value; RaisePropertyChanged(() => MyProperty); } } This raises the property changed event using a lambda expression instead of the property name. Light reflection is used to get the name. This supports Intellisense and can easily be refactored. You can also broadcast a PropertyChangedMessage using the Messenger.Default instance with: private int _myProperty; public int MyProperty { get { return _myProperty; } set { if (_myProperty == value) { return; } var oldValue = _myProperty; _myProperty = value; RaisePropertyChanged(() => MyProperty, oldValue, value, true); } } Using no arguments When the RaisePropertyChanged method is called within a setter, you can also omit the property name altogether. This will fail if executed outside of the setter however. Also, to avoid confusion, there is no way to broadcast the PropertyChangedMessage using this syntax. private int _myProperty; public int MyProperty { get { return _myProperty; } set { if (_myProperty == value) { return; } _myProperty = value; RaisePropertyChanged(); } } The old way Of course the “old” way is still supported, without broadcast: public const string MyPropertyName = "MyProperty"; private int _myProperty; public int MyProperty { get { return _myProperty; } set { if (_myProperty == value) { return; } _myProperty = value; RaisePropertyChanged(MyPropertyName); } } And with broadcast: public const string MyPropertyName = "MyProperty"; private int _myProperty; public int MyProperty { get { return _myProperty; } set { if (_myProperty == value) { return; } var oldValue = _myProperty; _myProperty = value; RaisePropertyChanged(MyPropertyName, oldValue, value, true); } } Performance considerations It is notorious that using reflection takes more time than using a string constant to get the property name. However, after measuring for all platforms, I found the differences to be very small. I will measure more and submit the results to the community for evaluation, because some of the results are actually surprising (for example, using the Messenger to broadcast a PropertyChangedMessage does not significantly increase the time taken to raise the PropertyChanged event and update the bindings). For now, I submit this code to you, and would be delighted to hear about your own results. Raising the CanExecuteChanged event manually In WPF, until now, the CanExecuteChanged event for a RelayCommand was raised automatically. Or rather, it was attempted to be raised, using a feature that is only available in WPF called the CommandManager. This class monitors the UI and when something occurs, it queries the state of the CanExecute delegate for all the commands. However, this proved unreliable for the purpose of MVVM: Since very often the value of the CanExecute delegate changes according to non-UI events (for example something changing in the viewmodel or in the model), raising the CanExecuteChanged event manually is necessary. In Silverlight, the CommandManager does not exist, so we had to raise the event manually from the start. This proved more reliable, and I now changed the WPF implementation of the RaiseCanExecuteChanged method to be the exact same in WPF than in Silverlight. For instance, if a command must be enabled when a string property is set to a value other than null or empty string, you can do: public MainViewModel() { MyTestCommand = new RelayCommand( () => DoSomething(), () => !string.IsNullOrEmpty(MyProperty)); } public const string MyPropertyName = "MyProperty"; private string _myProperty = string.Empty; public string MyProperty { get { return _myProperty; } set { if (_myProperty == value) { return; } _myProperty = value; RaisePropertyChanged(MyPropertyName); MyTestCommand.RaiseCanExecuteChanged(); } } Logo update I made a minor change to the logo: Some people found the lack of the word “light” (as in MVVM Light Toolkit) confusing. I thought it was cool, because the feather suggests the idea of lightness, however I can see the point. So I added the word “light” to the logo. Things should be quite clear now. What’s next? This is only the first of a series of releases that will bring MVVM Light to V4. In the next weeks, I will continue to add some very requested features and correct some issues in the code. I will probably continue this fashion of releasing the changes to the public as source code through Codeplex. I would be very interested to hear what you think of that, and to get feedback about the changes. Cheers, Laurent   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • WPF DataGrid AutoColumn generation via ICustomTypeDescriptor.

    - by panamack
    In a test project I've managed to AutoGenerate WPF DataGrid columns in the following scenario, where the data is stored in a Dictionary and binding is performed via PropertyDescriptors: public class People:List<Person>{ ... } public class Person:Dictionary<string,string>,INotifyPropertyChanged,ICustomTypeDescriptor { } The problem I'm having is in my real life project I'm using MVVM so it's *People*ViewModel which inherits ViewModelBase and hence can't inherit List<Person>. I've tried implementing IList<Person> instead with an internal List<Person> and explicitly setting the DataContext to an IList<Person> reference but that didn't work. I've seen a similar post on binding a win forms DataGridView here, so I'm wondering if the same sort of logic applies in WPF and primarily, what exactly causes the ICustomTypeDescriptor implementation to be picked up when inheriting List<T> that is missing when you simply implement IList<T> instead.

    Read the article

  • Cleanup vs Dispose(bool) in MVVM-light

    - by Budda
    In the lastest version of MVVM-light (V3 SP1) both "Dispose()" and "Dipose(bool)" methods in ViewModel class are marked Do not use this method anymore, it will be removed in a future version. Use ICleanup.Cleanup() instead Does this mean that IDisposable interface must not be implemented in all ViewModel classes that are derived from GalaSoft.MvvmLight.ViewModelBase (and cleanup must be overrided)? If yes, using can't be used for view-model instances... Probably I didn't understand something... Please clarify... What are the benefits of such cleaning up? Thanks.

    Read the article

  • Introducing the Earthquake Locator – A Bing Maps Silverlight Application, part 1

    - by Bobby Diaz
    Update: Live demo and source code now available!  The recent wave of earthquakes (no pun intended) being reported in the news got me wondering about the frequency and severity of earthquakes around the world. Since I’ve been doing a lot of Silverlight development lately, I decided to scratch my curiosity with a nice little Bing Maps application that will show the location and relative strength of recent seismic activity. Here is a list of technologies this application will utilize, so be sure to have everything downloaded and installed if you plan on following along. Silverlight 3 WCF RIA Services Bing Maps Silverlight Control * Managed Extensibility Framework (optional) MVVM Light Toolkit (optional) log4net (optional) * If you are new to Bing Maps or have not signed up for a Developer Account, you will need to visit www.bingmapsportal.com to request a Bing Maps key for your application. Getting Started We start out by creating a new Silverlight Application called EarthquakeLocator and specify that we want to automatically create the Web Application Project with RIA Services enabled. I cleaned up the web app by removing the Default.aspx and EarthquakeLocatorTestPage.html. Then I renamed the EarthquakeLocatorTestPage.aspx to Default.aspx and set it as my start page. I also set the development server to use a specific port, as shown below. RIA Services Next, I created a Services folder in the EarthquakeLocator.Web project and added a new Domain Service Class called EarthquakeService.cs. This is the RIA Services Domain Service that will provide earthquake data for our client application. I am not using LINQ to SQL or Entity Framework, so I will use the <empty domain service class> option. We will be pulling data from an external Atom feed, but this example could just as easily pull data from a database or another web service. This is an important distinction to point out because each scenario I just mentioned could potentially use a different Domain Service base class (i.e. LinqToSqlDomainService<TDataContext>). Now we can start adding Query methods to our EarthquakeService that pull data from the USGS web site. Here is the complete code for our service class: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.ServiceModel.Syndication; using System.Web.DomainServices; using System.Web.Ria; using System.Xml; using log4net; using EarthquakeLocator.Web.Model;   namespace EarthquakeLocator.Web.Services {     /// <summary>     /// Provides earthquake data to client applications.     /// </summary>     [EnableClientAccess()]     public class EarthquakeService : DomainService     {         private static readonly ILog log = LogManager.GetLogger(typeof(EarthquakeService));           // USGS Data Feeds: http://earthquake.usgs.gov/earthquakes/catalogs/         private const string FeedForPreviousDay =             "http://earthquake.usgs.gov/earthquakes/catalogs/1day-M2.5.xml";         private const string FeedForPreviousWeek =             "http://earthquake.usgs.gov/earthquakes/catalogs/7day-M2.5.xml";           /// <summary>         /// Gets the earthquake data for the previous week.         /// </summary>         /// <returns>A queryable collection of <see cref="Earthquake"/> objects.</returns>         public IQueryable<Earthquake> GetEarthquakes()         {             var feed = GetFeed(FeedForPreviousWeek);             var list = new List<Earthquake>();               if ( feed != null )             {                 foreach ( var entry in feed.Items )                 {                     var quake = CreateEarthquake(entry);                     if ( quake != null )                     {                         list.Add(quake);                     }                 }             }               return list.AsQueryable();         }           /// <summary>         /// Creates an <see cref="Earthquake"/> object for each entry in the Atom feed.         /// </summary>         /// <param name="entry">The Atom entry.</param>         /// <returns></returns>         private Earthquake CreateEarthquake(SyndicationItem entry)         {             Earthquake quake = null;             string title = entry.Title.Text;             string summary = entry.Summary.Text;             string point = GetElementValue<String>(entry, "point");             string depth = GetElementValue<String>(entry, "elev");             string utcTime = null;             string localTime = null;             string depthDesc = null;             double? magnitude = null;             double? latitude = null;             double? longitude = null;             double? depthKm = null;               if ( !String.IsNullOrEmpty(title) && title.StartsWith("M") )             {                 title = title.Substring(2, title.IndexOf(',')-3).Trim();                 magnitude = TryParse(title);             }             if ( !String.IsNullOrEmpty(point) )             {                 var values = point.Split(' ');                 if ( values.Length == 2 )                 {                     latitude = TryParse(values[0]);                     longitude = TryParse(values[1]);                 }             }             if ( !String.IsNullOrEmpty(depth) )             {                 depthKm = TryParse(depth);                 if ( depthKm != null )                 {                     depthKm = Math.Round((-1 * depthKm.Value) / 100, 2);                 }             }             if ( !String.IsNullOrEmpty(summary) )             {                 summary = summary.Replace("</p>", "");                 var values = summary.Split(                     new string[] { "<p>" },                     StringSplitOptions.RemoveEmptyEntries);                   if ( values.Length == 3 )                 {                     var times = values[1].Split(                         new string[] { "<br>" },                         StringSplitOptions.RemoveEmptyEntries);                       if ( times.Length > 0 )                     {                         utcTime = times[0];                     }                     if ( times.Length > 1 )                     {                         localTime = times[1];                     }                       depthDesc = values[2];                     depthDesc = "Depth: " + depthDesc.Substring(depthDesc.IndexOf(":") + 2);                 }             }               if ( latitude != null && longitude != null )             {                 quake = new Earthquake()                 {                     Id = entry.Id,                     Title = entry.Title.Text,                     Summary = entry.Summary.Text,                     Date = entry.LastUpdatedTime.DateTime,                     Url = entry.Links.Select(l => Path.Combine(l.BaseUri.OriginalString,                         l.Uri.OriginalString)).FirstOrDefault(),                     Age = entry.Categories.Where(c => c.Label == "Age")                         .Select(c => c.Name).FirstOrDefault(),                     Magnitude = magnitude.GetValueOrDefault(),                     Latitude = latitude.GetValueOrDefault(),                     Longitude = longitude.GetValueOrDefault(),                     DepthInKm = depthKm.GetValueOrDefault(),                     DepthDesc = depthDesc,                     UtcTime = utcTime,                     LocalTime = localTime                 };             }               return quake;         }           private T GetElementValue<T>(SyndicationItem entry, String name)         {             var el = entry.ElementExtensions.Where(e => e.OuterName == name).FirstOrDefault();             T value = default(T);               if ( el != null )             {                 value = el.GetObject<T>();             }               return value;         }           private double? TryParse(String value)         {             double d;             if ( Double.TryParse(value, out d) )             {                 return d;             }             return null;         }           /// <summary>         /// Gets the feed at the specified URL.         /// </summary>         /// <param name="url">The URL.</param>         /// <returns>A <see cref="SyndicationFeed"/> object.</returns>         public static SyndicationFeed GetFeed(String url)         {             SyndicationFeed feed = null;               try             {                 log.Debug("Loading RSS feed: " + url);                   using ( var reader = XmlReader.Create(url) )                 {                     feed = SyndicationFeed.Load(reader);                 }             }             catch ( Exception ex )             {                 log.Error("Error occurred while loading RSS feed: " + url, ex);             }               return feed;         }     } }   The only method that will be generated in the client side proxy class, EarthquakeContext, will be the GetEarthquakes() method. The reason being that it is the only public instance method and it returns an IQueryable<Earthquake> collection that can be consumed by the client application. GetEarthquakes() calls the static GetFeed(String) method, which utilizes the built in SyndicationFeed API to load the external data feed. You will need to add a reference to the System.ServiceModel.Web library in order to take advantage of the RSS/Atom reader. The API will also allow you to create your own feeds to serve up in your applications. Model I have also created a Model folder and added a new class, Earthquake.cs. The Earthquake object will hold the various properties returned from the Atom feed. Here is a sample of the code for that class. Notice the [Key] attribute on the Id property, which is required by RIA Services to uniquely identify the entity. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ComponentModel.DataAnnotations;   namespace EarthquakeLocator.Web.Model {     /// <summary>     /// Represents an earthquake occurrence and related information.     /// </summary>     [DataContract]     public class Earthquake     {         /// <summary>         /// Gets or sets the id.         /// </summary>         /// <value>The id.</value>         [Key]         [DataMember]         public string Id { get; set; }           /// <summary>         /// Gets or sets the title.         /// </summary>         /// <value>The title.</value>         [DataMember]         public string Title { get; set; }           /// <summary>         /// Gets or sets the summary.         /// </summary>         /// <value>The summary.</value>         [DataMember]         public string Summary { get; set; }           // additional properties omitted     } }   View Model The recent trend to use the MVVM pattern for WPF and Silverlight provides a great way to separate the data and behavior logic out of the user interface layer of your client applications. I have chosen to use the MVVM Light Toolkit for the Earthquake Locator, but there are other options out there if you prefer another library. That said, I went ahead and created a ViewModel folder in the Silverlight project and added a EarthquakeViewModel class that derives from ViewModelBase. Here is the code: using System; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using Microsoft.Maps.MapControl; using GalaSoft.MvvmLight; using EarthquakeLocator.Web.Model; using EarthquakeLocator.Web.Services;   namespace EarthquakeLocator.ViewModel {     /// <summary>     /// Provides data for views displaying earthquake information.     /// </summary>     public class EarthquakeViewModel : ViewModelBase     {         [Import]         public EarthquakeContext Context;           /// <summary>         /// Initializes a new instance of the <see cref="EarthquakeViewModel"/> class.         /// </summary>         public EarthquakeViewModel()         {             var catalog = new AssemblyCatalog(GetType().Assembly);             var container = new CompositionContainer(catalog);             container.ComposeParts(this);             Initialize();         }           /// <summary>         /// Initializes a new instance of the <see cref="EarthquakeViewModel"/> class.         /// </summary>         /// <param name="context">The context.</param>         public EarthquakeViewModel(EarthquakeContext context)         {             Context = context;             Initialize();         }           private void Initialize()         {             MapCenter = new Location(20, -170);             ZoomLevel = 2;         }           #region Private Methods           private void OnAutoLoadDataChanged()         {             LoadEarthquakes();         }           private void LoadEarthquakes()         {             var query = Context.GetEarthquakesQuery();             Context.Earthquakes.Clear();               Context.Load(query, (op) =>             {                 if ( !op.HasError )                 {                     foreach ( var item in op.Entities )                     {                         Earthquakes.Add(item);                     }                 }             }, null);         }           #endregion Private Methods           #region Properties           private bool autoLoadData;         /// <summary>         /// Gets or sets a value indicating whether to auto load data.         /// </summary>         /// <value><c>true</c> if auto loading data; otherwise, <c>false</c>.</value>         public bool AutoLoadData         {             get { return autoLoadData; }             set             {                 if ( autoLoadData != value )                 {                     autoLoadData = value;                     RaisePropertyChanged("AutoLoadData");                     OnAutoLoadDataChanged();                 }             }         }           private ObservableCollection<Earthquake> earthquakes;         /// <summary>         /// Gets the collection of earthquakes to display.         /// </summary>         /// <value>The collection of earthquakes.</value>         public ObservableCollection<Earthquake> Earthquakes         {             get             {                 if ( earthquakes == null )                 {                     earthquakes = new ObservableCollection<Earthquake>();                 }                   return earthquakes;             }         }           private Location mapCenter;         /// <summary>         /// Gets or sets the map center.         /// </summary>         /// <value>The map center.</value>         public Location MapCenter         {             get { return mapCenter; }             set             {                 if ( mapCenter != value )                 {                     mapCenter = value;                     RaisePropertyChanged("MapCenter");                 }             }         }           private double zoomLevel;         /// <summary>         /// Gets or sets the zoom level.         /// </summary>         /// <value>The zoom level.</value>         public double ZoomLevel         {             get { return zoomLevel; }             set             {                 if ( zoomLevel != value )                 {                     zoomLevel = value;                     RaisePropertyChanged("ZoomLevel");                 }             }         }           #endregion Properties     } }   The EarthquakeViewModel class contains all of the properties that will be bound to by the various controls in our views. Be sure to read through the LoadEarthquakes() method, which handles calling the GetEarthquakes() method in our EarthquakeService via the EarthquakeContext proxy, and also transfers the loaded entities into the view model’s Earthquakes collection. Another thing to notice is what’s going on in the default constructor. I chose to use the Managed Extensibility Framework (MEF) for my composition needs, but you can use any dependency injection library or none at all. To allow the EarthquakeContext class to be discoverable by MEF, I added the following partial class so that I could supply the appropriate [Export] attribute: using System; using System.ComponentModel.Composition;   namespace EarthquakeLocator.Web.Services {     /// <summary>     /// The client side proxy for the EarthquakeService class.     /// </summary>     [Export]     public partial class EarthquakeContext     {     } }   One last piece I wanted to point out before moving on to the user interface, I added a client side partial class for the Earthquake entity that contains helper properties that we will bind to later: using System;   namespace EarthquakeLocator.Web.Model {     /// <summary>     /// Represents an earthquake occurrence and related information.     /// </summary>     public partial class Earthquake     {         /// <summary>         /// Gets the location based on the current Latitude/Longitude.         /// </summary>         /// <value>The location.</value>         public string Location         {             get { return String.Format("{0},{1}", Latitude, Longitude); }         }           /// <summary>         /// Gets the size based on the Magnitude.         /// </summary>         /// <value>The size.</value>         public double Size         {             get { return (Magnitude * 3); }         }     } }   View Now the fun part! Usually, I would create a Views folder to place all of my View controls in, but I took the easy way out and added the following XAML code to the default MainPage.xaml file. Be sure to add the bing prefix associating the Microsoft.Maps.MapControl namespace after adding the assembly reference to your project. The MVVM Light Toolkit project templates come with a ViewModelLocator class that you can use via a static resource, but I am instantiating the EarthquakeViewModel directly in my user control. I am setting the AutoLoadData property to true as a way to trigger the LoadEarthquakes() method call. The MapItemsControl found within the <bing:Map> control binds its ItemsSource property to the Earthquakes collection of the view model, and since it is an ObservableCollection<T>, we get the automatic two way data binding via the INotifyCollectionChanged interface. <UserControl x:Class="EarthquakeLocator.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"     xmlns:bing="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"     xmlns:vm="clr-namespace:EarthquakeLocator.ViewModel"     mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480" >     <UserControl.Resources>         <DataTemplate x:Key="EarthquakeTemplate">             <Ellipse Fill="Red" Stroke="Black" StrokeThickness="1"                      Width="{Binding Size}" Height="{Binding Size}"                      bing:MapLayer.Position="{Binding Location}"                      bing:MapLayer.PositionOrigin="Center">                 <ToolTipService.ToolTip>                     <StackPanel>                         <TextBlock Text="{Binding Title}" FontSize="14" FontWeight="Bold" />                         <TextBlock Text="{Binding UtcTime}" />                         <TextBlock Text="{Binding LocalTime}" />                         <TextBlock Text="{Binding DepthDesc}" />                     </StackPanel>                 </ToolTipService.ToolTip>             </Ellipse>         </DataTemplate>     </UserControl.Resources>       <UserControl.DataContext>         <vm:EarthquakeViewModel AutoLoadData="True" />     </UserControl.DataContext>       <Grid x:Name="LayoutRoot">           <bing:Map x:Name="map" CredentialsProvider="--Your-Bing-Maps-Key--"                   Center="{Binding MapCenter, Mode=TwoWay}"                   ZoomLevel="{Binding ZoomLevel, Mode=TwoWay}">             <bing:MapItemsControl ItemsSource="{Binding Earthquakes}"                                   ItemTemplate="{StaticResource EarthquakeTemplate}" />         </bing:Map>       </Grid> </UserControl>   The EarthquakeTemplate defines the Ellipse that will represent each earthquake, the Width and Height that are determined by the Magnitude, the Position on the map, and also the tooltip that will appear when we mouse over each data point. Running the application will give us the following result (shown with a tooltip example): That concludes this portion of our show but I plan on implementing additional functionality in later blog posts. Be sure to come back soon to see the next installments in this series. Enjoy!   Additional Resources USGS Earthquake Data Feeds Brad Abrams shows how RIA Services and MVVM can work together

    Read the article

  • Slides and Code from my Silverlight MVVM Talk at DevConnections

    - by dwahlin
    I had a great time at the DevConnections conference in Las Vegas this year where Visual Studio 2010 and Silverlight 4 were launched. While at the conference I had the opportunity to give a full-day Silverlight workshop as well as 4 different talks and met a lot of people developing applications in Silverlight. I also had a chance to appear on a live broadcast of Channel 9 with John Papa, Ward Bell and Shawn Wildermuth, record a video with Rick Strahl covering jQuery versus Silverlight and record a few podcasts on Silverlight and ASP.NET MVC 2.  It was a really busy 4 days but I had a lot of fun chatting with people and hearing about different business problems they were solving with ASP.NET and/or Silverlight. Thanks to everyone who attended my sessions and took the time to ask questions and stop by to talk one-on-one. One of the talks I gave covered the Model-View-ViewModel pattern and how it can be used to build architecturally sound applications. Topics covered in the talk included: Understanding the MVVM pattern Benefits of the MVVM pattern Creating a ViewModel class Implementing INotifyPropertyChanged in a ViewModelBase class Binding a ViewModel declaratively in XAML Binding a ViewModel with code ICommand and ButtonBase commanding support in Silverlight 4 Using InvokeCommandBehavior to handle additional commanding needs Working with ViewModels and Sample Data in Blend Messaging support with EventBus classes, EventAggregator and Messenger My personal take on code in a code-beside file (I’m all in favor of it when used appropriately for message boxes, child windows, animations, etc.) One of the samples I showed in the talk was intended to teach all of the concepts mentioned above while keeping things as simple as possible.  The sample demonstrates quite a few things you can do with Silverlight and the MVVM pattern so check it out and feel free to leave feedback about things you like, things you’d do differently or anything else. MVVM is simply a pattern, not a way of life so there are many different ways to implement it. If you’re new to the subject of MVVM check out the following resources. I wish this talk would’ve been recorded (especially since my live and canned demos all worked :-)) but these resources will help get you going quickly. Getting Started with the MVVM Pattern in Silverlight Applications Model-View-ViewModel (MVVM) Explained Laurent Bugnion’s Excellent Talk at MIX10     Download sample code and slides from my DevConnections talk     For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit http://www.thewahlingroup.com.

    Read the article

  • MVVM Light Toolkit V3 SP1 for Windows Phone 7

    - by Laurent Bugnion
    He he I start to sound like Microsoft… Anyway… I just released a service pack (SP1) for MVVM Light Toolkit V3. Why? Well mostly because I worked a bit more with the Windows Phone 7 tools that were released at MIX0, and I noticed a few things that could be better in the Windows Phone 7 template. Also, I only found out at MIX that you can actually install custom project templates for Visual Studio Express. For some reason I thought it was not possible. The best way to solve these issues is through a service pack, which consists of a few zip files. Simply follow the instructions on the “Installing Manually” page. You can go ahead and overwrite the files that were installed with V3, all the file structure and names are exactly the same. What? So what do you get in this service pack that was not already in V3? (for more info about what’s new in V3, check the What’s New page). Project and Item templates for Visual Studio 10 Express (phone edition). Unzip these files in your “My Documents” folder, and you can now create a new MVVM Light application in the WinPhone7 version of Visual Studio 2010 Express. Signed assemblies: All the assemblies are now signed, which is a requirement in certain build configurations. XML documentation files: Thanks to Matt Casto for pinging me and reminding me that I had forgotten to include them (doh). New and improved Windows Phone 7 assemblies and templates: This one deserves its own section (see below). What was wrong with the old Silverlight 3 assemblies in Windows Phone 7 projects? It was kind of weird. Functionality wise, it was working just right. However, if you noticed, the EventToCommand behavior was not visible in the Assets tab of Expression Blend, under Behaviors, where it should normally have been. The reason was that even though the Windows Phone 7 is using Silverlight 3, the System.Windows.Interactivity that Blend was expecting is the version that is normally used in Silverlight 4. Yeah, I know, it’s weird. This led me to create a specific version of these assemblies for the phone. The assemblies are located into C:\Program Files\Laurent Bugnion (GalaSoft)\Mvvm Light Toolkit\Binaries\WP7. There are 3 DLLs: GalaSoft.MvvmLight.WP7.dll with RelayCommand, Messenger and ViewModelBase GalaSoft.MvvmLight.Extras.WP7.dll with EventToCommand and DispatcherHelper System.Windows.Interactivity.dll which is the same DLL installed in the Blend SDK, and which is needed for the EventToCommand behavior to work. Happy coding! That’s all! Download and install the service pack according to the instructions on the Installation page, and create your first MVVM Light application for the phone (a blog post will follow later with more details).   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • Silverlight Recruiting Application Part 5 - Jobs Module / View

    Now we starting getting into a more code-heavy portion of this series, thankfully though this means the groundwork is all set for the most part and after adding the modules we will have a complete application that can be provided with full source. The Jobs module will have two concerns- adding and maintaining jobs that can then be broadcast out to the website. How they are displayed on the site will be handled by our admin system (which will just poll from this common database), so we aren't too concerned with that, but rather with getting the information into the system and allowing the backend administration/HR users to keep things up to date. Since there is a fair bit of information that we want to display, we're going to move editing to a separate view so we can get all that information in an easy-to-use spot. With all the files created for this module, the project looks something like this: And now... on to the code. XAML for the Job Posting View All we really need for the Job Posting View is a RadGridView and a few buttons. This will let us both show off records and perform operations on the records without much hassle. That XAML is going to look something like this: 01.<Grid x:Name="LayoutRoot" 02.Background="White"> 03.<Grid.RowDefinitions> 04.<RowDefinition Height="30" /> 05.<RowDefinition /> 06.</Grid.RowDefinitions> 07.<StackPanel Orientation="Horizontal"> 08.<Button x:Name="xAddRecordButton" 09.Content="Add Job" 10.Width="120" 11.cal:Click.Command="{Binding AddRecord}" 12.telerik:StyleManager.Theme="Windows7" /> 13.<Button x:Name="xEditRecordButton" 14.Content="Edit Job" 15.Width="120" 16.cal:Click.Command="{Binding EditRecord}" 17.telerik:StyleManager.Theme="Windows7" /> 18.</StackPanel> 19.<telerikGrid:RadGridView x:Name="xJobsGrid" 20.Grid.Row="1" 21.IsReadOnly="True" 22.AutoGenerateColumns="False" 23.ColumnWidth="*" 24.RowDetailsVisibilityMode="VisibleWhenSelected" 25.ItemsSource="{Binding MyJobs}" 26.SelectedItem="{Binding SelectedJob, Mode=TwoWay}" 27.command:SelectedItemChangedEventClass.Command="{Binding SelectedItemChanged}"> 28.<telerikGrid:RadGridView.Columns> 29.<telerikGrid:GridViewDataColumn Header="Job Title" 30.DataMemberBinding="{Binding JobTitle}" 31.UniqueName="JobTitle" /> 32.<telerikGrid:GridViewDataColumn Header="Location" 33.DataMemberBinding="{Binding Location}" 34.UniqueName="Location" /> 35.<telerikGrid:GridViewDataColumn Header="Resume Required" 36.DataMemberBinding="{Binding NeedsResume}" 37.UniqueName="NeedsResume" /> 38.<telerikGrid:GridViewDataColumn Header="CV Required" 39.DataMemberBinding="{Binding NeedsCV}" 40.UniqueName="NeedsCV" /> 41.<telerikGrid:GridViewDataColumn Header="Overview Required" 42.DataMemberBinding="{Binding NeedsOverview}" 43.UniqueName="NeedsOverview" /> 44.<telerikGrid:GridViewDataColumn Header="Active" 45.DataMemberBinding="{Binding IsActive}" 46.UniqueName="IsActive" /> 47.</telerikGrid:RadGridView.Columns> 48.</telerikGrid:RadGridView> 49.</Grid> I'll explain what's happening here by line numbers: Lines 11 and 16: Using the same type of click commands as we saw in the Menu module, we tie the button clicks to delegate commands in the viewmodel. Line 25: The source for the jobs will be a collection in the viewmodel. Line 26: We also bind the selected item to a public property from the viewmodel for use in code. Line 27: We've turned the event into a command so we can handle it via code in the viewmodel. So those first three probably make sense to you as far as Silverlight/WPF binding magic is concerned, but for line 27... This actually comes from something I read onDamien Schenkelman's blog back in the day for creating an attached behavior from any event. So, any time you see me using command:Whatever.Command, the backing for it is actually something like this: SelectedItemChangedEventBehavior.cs: 01.public class SelectedItemChangedEventBehavior : CommandBehaviorBase<Telerik.Windows.Controls.DataControl> 02.{ 03.public SelectedItemChangedEventBehavior(DataControl element) 04.: base(element) 05.{ 06.element.SelectionChanged += new EventHandler<SelectionChangeEventArgs>(element_SelectionChanged); 07.} 08.void element_SelectionChanged(object sender, SelectionChangeEventArgs e) 09.{ 10.// We'll only ever allow single selection, so will only need item index 0 11.base.CommandParameter = e.AddedItems[0]; 12.base.ExecuteCommand(); 13.} 14.} SelectedItemChangedEventClass.cs: 01.public class SelectedItemChangedEventClass 02.{ 03.#region The Command Stuff 04.public static ICommand GetCommand(DependencyObject obj) 05.{ 06.return (ICommand)obj.GetValue(CommandProperty); 07.} 08.public static void SetCommand(DependencyObject obj, ICommand value) 09.{ 10.obj.SetValue(CommandProperty, value); 11.} 12.public static readonly DependencyProperty CommandProperty = 13.DependencyProperty.RegisterAttached("Command", typeof(ICommand), 14.typeof(SelectedItemChangedEventClass), new PropertyMetadata(OnSetCommandCallback)); 15.public static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) 16.{ 17.DataControl element = dependencyObject as DataControl; 18.if (element != null) 19.{ 20.SelectedItemChangedEventBehavior behavior = GetOrCreateBehavior(element); 21.behavior.Command = e.NewValue as ICommand; 22.} 23.} 24.#endregion 25.public static SelectedItemChangedEventBehavior GetOrCreateBehavior(DataControl element) 26.{ 27.SelectedItemChangedEventBehavior behavior = element.GetValue(SelectedItemChangedEventBehaviorProperty) as SelectedItemChangedEventBehavior; 28.if (behavior == null) 29.{ 30.behavior = new SelectedItemChangedEventBehavior(element); 31.element.SetValue(SelectedItemChangedEventBehaviorProperty, behavior); 32.} 33.return behavior; 34.} 35.public static SelectedItemChangedEventBehavior GetSelectedItemChangedEventBehavior(DependencyObject obj) 36.{ 37.return (SelectedItemChangedEventBehavior)obj.GetValue(SelectedItemChangedEventBehaviorProperty); 38.} 39.public static void SetSelectedItemChangedEventBehavior(DependencyObject obj, SelectedItemChangedEventBehavior value) 40.{ 41.obj.SetValue(SelectedItemChangedEventBehaviorProperty, value); 42.} 43.public static readonly DependencyProperty SelectedItemChangedEventBehaviorProperty = 44.DependencyProperty.RegisterAttached("SelectedItemChangedEventBehavior", 45.typeof(SelectedItemChangedEventBehavior), typeof(SelectedItemChangedEventClass), null); 46.} These end up looking very similar from command to command, but in a nutshell you create a command based on any event, determine what the parameter for it will be, then execute. It attaches via XAML and ties to a DelegateCommand in the viewmodel, so you get the full event experience (since some controls get a bit event-rich for added functionality). Simple enough, right? Viewmodel for the Job Posting View The Viewmodel is going to need to handle all events going back and forth, maintaining interactions with the data we are using, and both publishing and subscribing to events. Rather than breaking this into tons of little pieces, I'll give you a nice view of the entire viewmodel and then hit up the important points line-by-line: 001.public class JobPostingViewModel : ViewModelBase 002.{ 003.private readonly IEventAggregator eventAggregator; 004.private readonly IRegionManager regionManager; 005.public DelegateCommand<object> AddRecord { get; set; } 006.public DelegateCommand<object> EditRecord { get; set; } 007.public DelegateCommand<object> SelectedItemChanged { get; set; } 008.public RecruitingContext context; 009.private QueryableCollectionView _myJobs; 010.public QueryableCollectionView MyJobs 011.{ 012.get { return _myJobs; } 013.} 014.private QueryableCollectionView _selectionJobActionHistory; 015.public QueryableCollectionView SelectedJobActionHistory 016.{ 017.get { return _selectionJobActionHistory; } 018.} 019.private JobPosting _selectedJob; 020.public JobPosting SelectedJob 021.{ 022.get { return _selectedJob; } 023.set 024.{ 025.if (value != _selectedJob) 026.{ 027._selectedJob = value; 028.NotifyChanged("SelectedJob"); 029.} 030.} 031.} 032.public SubscriptionToken editToken = new SubscriptionToken(); 033.public SubscriptionToken addToken = new SubscriptionToken(); 034.public JobPostingViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 035.{ 036.// set Unity items 037.this.eventAggregator = eventAgg; 038.this.regionManager = regionmanager; 039.// load our context 040.context = new RecruitingContext(); 041.this._myJobs = new QueryableCollectionView(context.JobPostings); 042.context.Load(context.GetJobPostingsQuery()); 043.// set command events 044.this.AddRecord = new DelegateCommand<object>(this.AddNewRecord); 045.this.EditRecord = new DelegateCommand<object>(this.EditExistingRecord); 046.this.SelectedItemChanged = new DelegateCommand<object>(this.SelectedRecordChanged); 047.SetSubscriptions(); 048.} 049.#region DelegateCommands from View 050.public void AddNewRecord(object obj) 051.{ 052.this.eventAggregator.GetEvent<AddJobEvent>().Publish(true); 053.} 054.public void EditExistingRecord(object obj) 055.{ 056.if (_selectedJob == null) 057.{ 058.this.eventAggregator.GetEvent<NotifyUserEvent>().Publish("No job selected."); 059.} 060.else 061.{ 062.this._myJobs.EditItem(this._selectedJob); 063.this.eventAggregator.GetEvent<EditJobEvent>().Publish(this._selectedJob); 064.} 065.} 066.public void SelectedRecordChanged(object obj) 067.{ 068.if (obj.GetType() == typeof(ActionHistory)) 069.{ 070.// event bubbles up so we don't catch items from the ActionHistory grid 071.} 072.else 073.{ 074.JobPosting job = obj as JobPosting; 075.GrabHistory(job.PostingID); 076.} 077.} 078.#endregion 079.#region Subscription Declaration and Events 080.public void SetSubscriptions() 081.{ 082.EditJobCompleteEvent editComplete = eventAggregator.GetEvent<EditJobCompleteEvent>(); 083.if (editToken != null) 084.editComplete.Unsubscribe(editToken); 085.editToken = editComplete.Subscribe(this.EditCompleteEventHandler); 086.AddJobCompleteEvent addComplete = eventAggregator.GetEvent<AddJobCompleteEvent>(); 087.if (addToken != null) 088.addComplete.Unsubscribe(addToken); 089.addToken = addComplete.Subscribe(this.AddCompleteEventHandler); 090.} 091.public void EditCompleteEventHandler(bool complete) 092.{ 093.if (complete) 094.{ 095.JobPosting thisJob = _myJobs.CurrentEditItem as JobPosting; 096.this._myJobs.CommitEdit(); 097.this.context.SubmitChanges((s) => 098.{ 099.ActionHistory myAction = new ActionHistory(); 100.myAction.PostingID = thisJob.PostingID; 101.myAction.Description = String.Format("Job '{0}' has been edited by {1}", thisJob.JobTitle, "default user"); 102.myAction.TimeStamp = DateTime.Now; 103.eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 104.} 105., null); 106.} 107.else 108.{ 109.this._myJobs.CancelEdit(); 110.} 111.this.MakeMeActive(this.regionManager, "MainRegion", "JobPostingsView"); 112.} 113.public void AddCompleteEventHandler(JobPosting job) 114.{ 115.if (job == null) 116.{ 117.// do nothing, new job add cancelled 118.} 119.else 120.{ 121.this.context.JobPostings.Add(job); 122.this.context.SubmitChanges((s) => 123.{ 124.ActionHistory myAction = new ActionHistory(); 125.myAction.PostingID = job.PostingID; 126.myAction.Description = String.Format("Job '{0}' has been added by {1}", job.JobTitle, "default user"); 127.myAction.TimeStamp = DateTime.Now; 128.eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 129.} 130., null); 131.} 132.this.MakeMeActive(this.regionManager, "MainRegion", "JobPostingsView"); 133.} 134.#endregion 135.public void GrabHistory(int postID) 136.{ 137.context.ActionHistories.Clear(); 138._selectionJobActionHistory = new QueryableCollectionView(context.ActionHistories); 139.context.Load(context.GetHistoryForJobQuery(postID)); 140.} Taking it from the top, we're injecting an Event Aggregator and Region Manager for use down the road and also have the public DelegateCommands (just like in the Menu module). We also grab a reference to our context, which we'll obviously need for data, then set up a few fields with public properties tied to them. We're also setting subscription tokens, which we have not yet seen but I will get into below. The AddNewRecord (50) and EditExistingRecord (54) methods should speak for themselves for functionality, the one thing of note is we're sending events off to the Event Aggregator which some module, somewhere will take care of. Since these aren't entirely relying on one another, the Jobs View doesn't care if anyone is listening, but it will publish AddJobEvent (52), NotifyUserEvent (58) and EditJobEvent (63)regardless. Don't mind the GrabHistory() method so much, that is just grabbing history items (visibly being created in the SubmitChanges callbacks), and adding them to the database. Every action will trigger a history event, so we'll know who modified what and when, just in case. ;) So where are we at? Well, if we click to Add a job, we publish an event, if we edit a job, we publish an event with the selected record (attained through the magic of binding). Where is this all going though? To the Viewmodel, of course! XAML for the AddEditJobView This is pretty straightforward except for one thing, noted below: 001.<Grid x:Name="LayoutRoot" 002.Background="White"> 003.<Grid x:Name="xEditGrid" 004.Margin="10" 005.validationHelper:ValidationScope.Errors="{Binding Errors}"> 006.<Grid.Background> 007.<LinearGradientBrush EndPoint="0.5,1" 008.StartPoint="0.5,0"> 009.<GradientStop Color="#FFC7C7C7" 010.Offset="0" /> 011.<GradientStop Color="#FFF6F3F3" 012.Offset="1" /> 013.</LinearGradientBrush> 014.</Grid.Background> 015.<Grid.RowDefinitions> 016.<RowDefinition Height="40" /> 017.<RowDefinition Height="40" /> 018.<RowDefinition Height="40" /> 019.<RowDefinition Height="100" /> 020.<RowDefinition Height="100" /> 021.<RowDefinition Height="100" /> 022.<RowDefinition Height="40" /> 023.<RowDefinition Height="40" /> 024.<RowDefinition Height="40" /> 025.</Grid.RowDefinitions> 026.<Grid.ColumnDefinitions> 027.<ColumnDefinition Width="150" /> 028.<ColumnDefinition Width="150" /> 029.<ColumnDefinition Width="300" /> 030.<ColumnDefinition Width="100" /> 031.</Grid.ColumnDefinitions> 032.<!-- Title --> 033.<TextBlock Margin="8" 034.Text="{Binding AddEditString}" 035.TextWrapping="Wrap" 036.Grid.Column="1" 037.Grid.ColumnSpan="2" 038.FontSize="16" /> 039.<!-- Data entry area--> 040. 041.<TextBlock Margin="8,0,0,0" 042.Style="{StaticResource LabelTxb}" 043.Grid.Row="1" 044.Text="Job Title" 045.VerticalAlignment="Center" /> 046.<TextBox x:Name="xJobTitleTB" 047.Margin="0,8" 048.Grid.Column="1" 049.Grid.Row="1" 050.Text="{Binding activeJob.JobTitle, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 051.Grid.ColumnSpan="2" /> 052.<TextBlock Margin="8,0,0,0" 053.Grid.Row="2" 054.Text="Location" 055.d:LayoutOverrides="Height" 056.VerticalAlignment="Center" /> 057.<TextBox x:Name="xLocationTB" 058.Margin="0,8" 059.Grid.Column="1" 060.Grid.Row="2" 061.Text="{Binding activeJob.Location, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 062.Grid.ColumnSpan="2" /> 063. 064.<TextBlock Margin="8,11,8,0" 065.Grid.Row="3" 066.Text="Description" 067.TextWrapping="Wrap" 068.VerticalAlignment="Top" /> 069. 070.<TextBox x:Name="xDescriptionTB" 071.Height="84" 072.TextWrapping="Wrap" 073.ScrollViewer.VerticalScrollBarVisibility="Auto" 074.Grid.Column="1" 075.Grid.Row="3" 076.Text="{Binding activeJob.Description, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 077.Grid.ColumnSpan="2" /> 078.<TextBlock Margin="8,11,8,0" 079.Grid.Row="4" 080.Text="Requirements" 081.TextWrapping="Wrap" 082.VerticalAlignment="Top" /> 083. 084.<TextBox x:Name="xRequirementsTB" 085.Height="84" 086.TextWrapping="Wrap" 087.ScrollViewer.VerticalScrollBarVisibility="Auto" 088.Grid.Column="1" 089.Grid.Row="4" 090.Text="{Binding activeJob.Requirements, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 091.Grid.ColumnSpan="2" /> 092.<TextBlock Margin="8,11,8,0" 093.Grid.Row="5" 094.Text="Qualifications" 095.TextWrapping="Wrap" 096.VerticalAlignment="Top" /> 097. 098.<TextBox x:Name="xQualificationsTB" 099.Height="84" 100.TextWrapping="Wrap" 101.ScrollViewer.VerticalScrollBarVisibility="Auto" 102.Grid.Column="1" 103.Grid.Row="5" 104.Text="{Binding activeJob.Qualifications, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 105.Grid.ColumnSpan="2" /> 106.<!-- Requirements Checkboxes--> 107. 108.<CheckBox x:Name="xResumeRequiredCB" Margin="8,8,8,15" 109.Content="Resume Required" 110.Grid.Row="6" 111.Grid.ColumnSpan="2" 112.IsChecked="{Binding activeJob.NeedsResume, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 113. 114.<CheckBox x:Name="xCoverletterRequiredCB" Margin="8,8,8,15" 115.Content="Cover Letter Required" 116.Grid.Column="2" 117.Grid.Row="6" 118.IsChecked="{Binding activeJob.NeedsCV, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 119. 120.<CheckBox x:Name="xOverviewRequiredCB" Margin="8,8,8,15" 121.Content="Overview Required" 122.Grid.Row="7" 123.Grid.ColumnSpan="2" 124.IsChecked="{Binding activeJob.NeedsOverview, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 125. 126.<CheckBox x:Name="xJobActiveCB" Margin="8,8,8,15" 127.Content="Job is Active" 128.Grid.Column="2" 129.Grid.Row="7" 130.IsChecked="{Binding activeJob.IsActive, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 131. 132.<!-- Buttons --> 133. 134.<Button x:Name="xAddEditButton" Margin="8,8,0,10" 135.Content="{Binding AddEditButtonString}" 136.cal:Click.Command="{Binding AddEditCommand}" 137.Grid.Column="2" 138.Grid.Row="8" 139.HorizontalAlignment="Left" 140.Width="125" 141.telerik:StyleManager.Theme="Windows7" /> 142. 143.<Button x:Name="xCancelButton" HorizontalAlignment="Right" 144.Content="Cancel" 145.cal:Click.Command="{Binding CancelCommand}" 146.Margin="0,8,8,10" 147.Width="125" 148.Grid.Column="2" 149.Grid.Row="8" 150.telerik:StyleManager.Theme="Windows7" /> 151.</Grid> 152.</Grid> The 'validationHelper:ValidationScope' line may seem odd. This is a handy little trick for catching current and would-be validation errors when working in this whole setup. This all comes from an approach found on theJoy Of Code blog, although it looks like the story for this will be changing slightly with new advances in SL4/WCF RIA Services, so this section can definitely get an overhaul a little down the road. The code is the fun part of all this, so let us see what's happening under the hood. Viewmodel for the AddEditJobView We are going to see some of the same things happening here, so I'll skip over the repeat info and get right to the good stuff: 001.public class AddEditJobViewModel : ViewModelBase 002.{ 003.private readonly IEventAggregator eventAggregator; 004.private readonly IRegionManager regionManager; 005. 006.public RecruitingContext context; 007. 008.private JobPosting _activeJob; 009.public JobPosting activeJob 010.{ 011.get { return _activeJob; } 012.set 013.{ 014.if (_activeJob != value) 015.{ 016._activeJob = value; 017.NotifyChanged("activeJob"); 018.} 019.} 020.} 021. 022.public bool isNewJob; 023. 024.private string _addEditString; 025.public string AddEditString 026.{ 027.get { return _addEditString; } 028.set 029.{ 030.if (_addEditString != value) 031.{ 032._addEditString = value; 033.NotifyChanged("AddEditString"); 034.} 035.} 036.} 037. 038.private string _addEditButtonString; 039.public string AddEditButtonString 040.{ 041.get { return _addEditButtonString; } 042.set 043.{ 044.if (_addEditButtonString != value) 045.{ 046._addEditButtonString = value; 047.NotifyChanged("AddEditButtonString"); 048.} 049.} 050.} 051. 052.public SubscriptionToken addJobToken = new SubscriptionToken(); 053.public SubscriptionToken editJobToken = new SubscriptionToken(); 054. 055.public DelegateCommand<object> AddEditCommand { get; set; } 056.public DelegateCommand<object> CancelCommand { get; set; } 057. 058.private ObservableCollection<ValidationError> _errors = new ObservableCollection<ValidationError>(); 059.public ObservableCollection<ValidationError> Errors 060.{ 061.get { return _errors; } 062.} 063. 064.private ObservableCollection<ValidationResult> _valResults = new ObservableCollection<ValidationResult>(); 065.public ObservableCollection<ValidationResult> ValResults 066.{ 067.get { return this._valResults; } 068.} 069. 070.public AddEditJobViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 071.{ 072.// set Unity items 073.this.eventAggregator = eventAgg; 074.this.regionManager = regionmanager; 075. 076.context = new RecruitingContext(); 077. 078.AddEditCommand = new DelegateCommand<object>(this.AddEditJobCommand); 079.CancelCommand = new DelegateCommand<object>(this.CancelAddEditCommand); 080. 081.SetSubscriptions(); 082.} 083. 084.#region Subscription Declaration and Events 085. 086.public void SetSubscriptions() 087.{ 088.AddJobEvent addJob = this.eventAggregator.GetEvent<AddJobEvent>(); 089. 090.if (addJobToken != null) 091.addJob.Unsubscribe(addJobToken); 092. 093.addJobToken = addJob.Subscribe(this.AddJobEventHandler); 094. 095.EditJobEvent editJob = this.eventAggregator.GetEvent<EditJobEvent>(); 096. 097.if (editJobToken != null) 098.editJob.Unsubscribe(editJobToken); 099. 100.editJobToken = editJob.Subscribe(this.EditJobEventHandler); 101.} 102. 103.public void AddJobEventHandler(bool isNew) 104.{ 105.this.activeJob = null; 106.this.activeJob = new JobPosting(); 107.this.activeJob.IsActive = true; // We assume that we want a new job to go up immediately 108.this.isNewJob = true; 109.this.AddEditString = "Add New Job Posting"; 110.this.AddEditButtonString = "Add Job"; 111. 112.MakeMeActive(this.regionManager, "MainRegion", "AddEditJobView"); 113.} 114. 115.public void EditJobEventHandler(JobPosting editJob) 116.{ 117.this.activeJob = null; 118.this.activeJob = editJob; 119.this.isNewJob = false; 120.this.AddEditString = "Edit Job Posting"; 121.this.AddEditButtonString = "Edit Job"; 122. 123.MakeMeActive(this.regionManager, "MainRegion", "AddEditJobView"); 124.} 125. 126.#endregion 127. 128.#region DelegateCommands from View 129. 130.public void AddEditJobCommand(object obj) 131.{ 132.if (this.Errors.Count > 0) 133.{ 134.List<string> errorMessages = new List<string>(); 135. 136.foreach (var valR in this.Errors) 137.{ 138.errorMessages.Add(valR.Exception.Message); 139.} 140. 141.this.eventAggregator.GetEvent<DisplayValidationErrorsEvent>().Publish(errorMessages); 142. 143.} 144.else if (!Validator.TryValidateObject(this.activeJob, new ValidationContext(this.activeJob, null, null), _valResults, true)) 145.{ 146.List<string> errorMessages = new List<string>(); 147. 148.foreach (var valR in this._valResults) 149.{ 150.errorMessages.Add(valR.ErrorMessage); 151.} 152. 153.this._valResults.Clear(); 154. 155.this.eventAggregator.GetEvent<DisplayValidationErrorsEvent>().Publish(errorMessages); 156.} 157.else 158.{ 159.if (this.isNewJob) 160.{ 161.this.eventAggregator.GetEvent<AddJobCompleteEvent>().Publish(this.activeJob); 162.} 163.else 164.{ 165.this.eventAggregator.GetEvent<EditJobCompleteEvent>().Publish(true); 166.} 167.} 168.} 169. 170.public void CancelAddEditCommand(object obj) 171.{ 172.if (this.isNewJob) 173.{ 174.this.eventAggregator.GetEvent<AddJobCompleteEvent>().Publish(null); 175.} 176.else 177.{ 178.this.eventAggregator.GetEvent<EditJobCompleteEvent>().Publish(false); 179.} 180.} 181. 182.#endregion 183.} 184.} We start seeing something new on line 103- the AddJobEventHandler will create a new job and set that to the activeJob item on the ViewModel. When this is all set, the view calls that familiar MakeMeActive method to activate itself. I made a bit of a management call on making views self-activate like this, but I figured it works for one reason. As I create this application, views may not exist that I have in mind, so after a view receives its 'ping' from being subscribed to an event, it prepares whatever it needs to do and then goes active. This way if I don't have 'edit' hooked up, I can click as the day is long on the main view and won't get lost in an empty region. Total personal preference here. :) Everything else should again be pretty straightforward, although I do a bit of validation checking in the AddEditJobCommand, which can either fire off an event back to the main view/viewmodel if everything is a success or sent a list of errors to our notification module, which pops open a RadWindow with the alerts if any exist. As a bonus side note, here's what my WCF RIA Services metadata looks like for handling all of the validation: private JobPostingMetadata() { } [StringLength(2500, ErrorMessage = "Description should be more than one and less than 2500 characters.", MinimumLength = 1)] [Required(ErrorMessage = "Description is required.")] public string Description; [Required(ErrorMessage="Active Status is Required")] public bool IsActive; [StringLength(100, ErrorMessage = "Posting title must be more than 3 but less than 100 characters.", MinimumLength = 3)] [Required(ErrorMessage = "Job Title is required.")] public bool JobTitle; [Required] public string Location; public bool NeedsCV; public bool NeedsOverview; public bool NeedsResume; public int PostingID; [Required(ErrorMessage="Qualifications are required.")] [StringLength(2500, ErrorMessage="Qualifications should be more than one and less than 2500 characters.", MinimumLength=1)] public string Qualifications; [StringLength(2500, ErrorMessage = "Requirements should be more than one and less than 2500 characters.", MinimumLength = 1)] [Required(ErrorMessage="Requirements are required.")] public string Requirements;   The RecruitCB Alternative See all that Xaml I pasted above? Those are now two pieces sitting in the JobsView.xaml file now. The only real difference is that the xEditGrid now sits in the same place as xJobsGrid, with visibility swapping out between the two for a quick switch. I also took out all the cal: and command: command references and replaced Button events with clicks and the Grid selection command replaced with a SelectedItemChanged event. Also, at the bottom of the xEditGrid after the last button, I add a ValidationSummary (with Visibility=Collapsed) to catch any errors that are popping up. Simple as can be, and leads to this being the single code-behind file: 001.public partial class JobsView : UserControl 002.{ 003.public RecruitingContext context; 004.public JobPosting activeJob; 005.public bool isNew; 006.private ObservableCollection<ValidationResult> _valResults = new ObservableCollection<ValidationResult>(); 007.public ObservableCollection<ValidationResult> ValResults 008.{ 009.get { return this._valResults; } 010.} 011.public JobsView() 012.{ 013.InitializeComponent(); 014.this.Loaded += new RoutedEventHandler(JobsView_Loaded); 015.} 016.void JobsView_Loaded(object sender, RoutedEventArgs e) 017.{ 018.context = new RecruitingContext(); 019.xJobsGrid.ItemsSource = context.JobPostings; 020.context.Load(context.GetJobPostingsQuery()); 021.} 022.private void xAddRecordButton_Click(object sender, RoutedEventArgs e) 023.{ 024.activeJob = new JobPosting(); 025.isNew = true; 026.xAddEditTitle.Text = "Add a Job Posting"; 027.xAddEditButton.Content = "Add"; 028.xEditGrid.DataContext = activeJob; 029.HideJobsGrid(); 030.} 031.private void xEditRecordButton_Click(object sender, RoutedEventArgs e) 032.{ 033.activeJob = xJobsGrid.SelectedItem as JobPosting; 034.isNew = false; 035.xAddEditTitle.Text = "Edit a Job Posting"; 036.xAddEditButton.Content = "Edit"; 037.xEditGrid.DataContext = activeJob; 038.HideJobsGrid(); 039.} 040.private void xAddEditButton_Click(object sender, RoutedEventArgs e) 041.{ 042.if (!Validator.TryValidateObject(this.activeJob, new ValidationContext(this.activeJob, null, null), _valResults, true)) 043.{ 044.List<string> errorMessages = new List<string>(); 045.foreach (var valR in this._valResults) 046.{ 047.errorMessages.Add(valR.ErrorMessage); 048.} 049.this._valResults.Clear(); 050.ShowErrors(errorMessages); 051.} 052.else if (xSummary.Errors.Count > 0) 053.{ 054.List<string> errorMessages = new List<string>(); 055.foreach (var err in xSummary.Errors) 056.{ 057.errorMessages.Add(err.Message); 058.} 059.ShowErrors(errorMessages); 060.} 061.else 062.{ 063.if (this.isNew) 064.{ 065.context.JobPostings.Add(activeJob); 066.context.SubmitChanges((s) => 067.{ 068.ActionHistory thisAction = new ActionHistory(); 069.thisAction.PostingID = activeJob.PostingID; 070.thisAction.Description = String.Format("Job '{0}' has been edited by {1}", activeJob.JobTitle, "default user"); 071.thisAction.TimeStamp = DateTime.Now; 072.context.ActionHistories.Add(thisAction); 073.context.SubmitChanges(); 074.}, null); 075.} 076.else 077.{ 078.context.SubmitChanges((s) => 079.{ 080.ActionHistory thisAction = new ActionHistory(); 081.thisAction.PostingID = activeJob.PostingID; 082.thisAction.Description = String.Format("Job '{0}' has been added by {1}", activeJob.JobTitle, "default user"); 083.thisAction.TimeStamp = DateTime.Now; 084.context.ActionHistories.Add(thisAction); 085.context.SubmitChanges(); 086.}, null); 087.} 088.ShowJobsGrid(); 089.} 090.} 091.private void xCancelButton_Click(object sender, RoutedEventArgs e) 092.{ 093.ShowJobsGrid(); 094.} 095.private void ShowJobsGrid() 096.{ 097.xAddEditRecordButtonPanel.Visibility = Visibility.Visible; 098.xEditGrid.Visibility = Visibility.Collapsed; 099.xJobsGrid.Visibility = Visibility.Visible; 100.} 101.private void HideJobsGrid() 102.{ 103.xAddEditRecordButtonPanel.Visibility = Visibility.Collapsed; 104.xJobsGrid.Visibility = Visibility.Collapsed; 105.xEditGrid.Visibility = Visibility.Visible; 106.} 107.private void ShowErrors(List<string> errorList) 108.{ 109.string nm = "Errors received: \n"; 110.foreach (string anerror in errorList) 111.nm += anerror + "\n"; 112.RadWindow.Alert(nm); 113.} 114.} The first 39 lines should be pretty familiar, not doing anything too unorthodox to get this up and running. Once we hit the xAddEditButton_Click on line 40, we're still doing pretty much the same things except instead of checking the ValidationHelper errors, we both run a check on the current activeJob object as well as check the ValidationSummary errors list. Once that is set, we again use the callback of context.SubmitChanges (lines 68 and 78) to create an ActionHistory which we will use to track these items down the line. That's all? Essentially... yes. If you look back through this post, most of the code and adventures we have taken were just to get things working in the MVVM/Prism setup. Since I have the whole 'module' self-contained in a single JobView+code-behind setup, I don't have to worry about things like sending events off into space for someone to pick up, communicating through an Infrastructure project, or even re-inventing events to be used with attached behaviors. Everything just kinda works, and again with much less code. Here's a picture of the MVVM and Code-behind versions on the Jobs and AddEdit views, but since the functionality is the same in both apps you still cannot tell them apart (for two-strike): Looking ahead, the Applicants module is effectively the same thing as the Jobs module, so most of the code is being cut-and-pasted back and forth with minor tweaks here and there. So that one is being taken care of by me behind the scenes. Next time, we get into a new world of fun- the interview scheduling module, which will pull from available jobs and applicants for each interview being scheduled, tying everything together with RadScheduler to the rescue. 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

  • MVVM Light Toolkit - RelayCommands, DelegateCommands, and ObservableObjects

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

    Read the article

  • Why can't I Bind a viewmodel property to a dependency property of a custom control

    - by Robert
    I want to use a color picker in my wpf application and I saw a nice looking one on this codeproject page. The control works fine until I want to connect the control to a viewmodel. I created a small test program with this viewmodel: public class ColorViewModel : ViewModelBase { public ColorViewModel() { LineColor = Brushes.Yellow; } SolidColorBrush _brushColor; public SolidColorBrush LineColor { get { return _brushColor; } set { _brushColor = value; RaisePropertyChanged(() => LineColor); } } } The test program has a textbox and the colorpicker controls: <StackPanel Orientation="Horizontal"> <TextBlock Text="Please Select a Color" FontWeight="Bold" Margin="10" Foreground="{Binding Path=LineColor, UpdateSourceTrigger=PropertyChanged}"/> <vw:ColorPickerControlView x:Name="ForeColorPicker" Margin="10" CurrentColor="{Binding Path=LineColor, UpdateSourceTrigger=PropertyChanged }"/> </StackPanel> In the loaded event of the window I set the viewmodel to the datacontext like this: DataContext = new ColorViewModel(); The problem is that I can't seem to bind the LineColor property of the viewmodel to the CurrentColor property of the ColorPickerControlView. The CurrentControl property of the ColorPickerControlView seems to be fine. The constructor looks like this: public ColorPickerControlView() { this.DataContext = this; InitializeComponent(); CommandBindings.Add(new CommandBinding(SelectColorCommand, SelectColorCommandExecute)); } In the constructor of the UserControl there is the line this.DataContext = this; I read that is is necessary to bind the dependency properties. Do I override this line when I set my viewmodel to the datacontext and is that why I can't bind to the CurrentColor property? Is there any workaround? Or did I make another mistake?

    Read the article

  • how to parametrize an import in a View?

    - by Gianluca Colucci
    Hello everybody, I am looking for some help and I hope that some good soul out there will be able to give me a hint :) In the app I am building, I have a View. When an instance of this View gets created, it "imports" (MEF) the corresponding ViewModel. Here some code: public partial class ContractEditorView : Window { public ContractEditorView () { InitializeComponent(); CompositionInitializer.SatisfyImports(this); } [Import(ViewModelTypes.ContractEditorViewModel)] public object ViewModel { set { DataContext = value; } } } and here is the export for the ViewModel: [PartCreationPolicy(CreationPolicy.NonShared)] [Export(ViewModelTypes.ContractEditorViewModel)] public class ContractEditorViewModel: ViewModelBase { public ContractEditorViewModel() { _contract = new Models.Contract(); } } Now, this works if I want to open a new window to create a new contract... But it does not if I want to use the same window to edit an existing contract... In other words, I would like to add a second construct both in the View and in the ViewModel: the original constructor would accept no parameters and therefore it would create a new contract; the new construct - the one I'd like to add - I'd like to pass an ID so that I can load a given entity... What I don't understand is how to pass this ID to the ViewModel import... Thanks in advance, Cheers, Gianluca.

    Read the article

  • Set form MinWidth and MinHeight based on child property

    - by Jon Mitchell
    I'm writing an application in WPF using the MVVM pattern. In my application I've got an IPopupWindowService which I use to create a popup dialog window. So to show a ViewModel in a popup window you'd do something like this: var container = ServiceLocator.Current.GetInstance<IUnityContainer>(); var popupService = container.Resolve<IPopupWindowService>(); var myViewModel = container.Resolve<IMyViewModel>(); popupService.Show((ViewModelBase)myViewModel); This is all well and good. What I want to do is be able to set the MinHeight and MinWidth on the View bound to myViewModel and have the popup window use those settings so that a user cannot make the window smaller than its contents will allow. At the moment when the user shrinks the window the contents stops resizing but the window doesn't. EDIT: I map my Views to my ViewModels in ResourceDictionarys like so: <DataTemplate DataType="{x:Type ViewModels:MyViewModel}"> <Views:MyView /> </DataTemplate> And my popup view looks like this: <Window x:Class="TheCompany.Cubit.Shell.Views.PopupWindowView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterOwner"> <DockPanel x:Name="panelContent"> <StackPanel HorizontalAlignment="Right" DockPanel.Dock="Bottom" Orientation="Horizontal" Visibility="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=ButtonPanelVisibility}"> <Button Width="75" IsDefault="True" x:Uid="ViewDialog_AcceptButton" Click="OnAcceptButtonClick" Margin="4">OK</Button> <Button Width="75" IsCancel="True" x:Uid="ViewDialog_CancelButton" Click="OnCancelButtonClick" Margin="0,4,4,4">Cancel</Button> </StackPanel> <ContentPresenter Content="{Binding}" /> </DockPanel>

    Read the article

  • Passing contextual info to Views in ASP.NET MVC

    - by Andrey
    I wonder - what is the best way to supply contextual (i.e. not related to any particular view, but to all views at the same time) info to a view (or to master page)? Consider the following scenario. Suppose we have an app that supports multiple UI languages. User can switch them via UI's widgets (something like tabs at the top of the page). Each language is rendered as a separate tab. Tab for the current language should not be rendered. To address these requirements I'm planning to have a javascript piece that will hide current's language tab on the client. To do this, I need current's language tab Id on the client. So, I need some way of passing the Id to master page (for it to be 'fused' into the js script). The best thing I can think of is that all my ViewModels should inherit some ViewModeBase that has a field to hold current language tab Id. Then, whatever View I'm rendering, this Id will always be available for the master page's hiding script. However, I'm concerned that this ViewModelBase can potentially grow in an uncontrolled fashion as number of such pieces of contextual info (like current language) will grow.. Any ideas?

    Read the article

  • International Radio Operators Alphabet in F# &amp; Silverlight &ndash; Part 2

    - by MarkPearl
    So the brunt of my my very complex F# code has been done. Now it’s just putting the Silverlight stuff in. The first thing I did was add a new project to my solution. I gave it a name and VS2010 did the rest of the magic in creating the .Web project etc. In this instance because I want to take the MVVM approach and make use of commanding I have decided to make the frontend a Silverlight4 project. I now need move my F# code into a proper Silverlight Library. Warning – when you create the Silverlight Library VS2010 will ask you whether you want it to be based on Silverlight3 or Silverlight4. I originally went for Silverlight4 only to discover when I tried to compile my solution that I was given an error… Error 12 F# runtime for Silverlight version v4.0 is not installed. Please go to http://go.microsoft.com/fwlink/?LinkId=177463 to download and install matching.. After asking around I discovered that the Silverlight4 F# runtime is not available yet. No problem, the suggestion was to change the F# Silverlight Library to a Silverlight3 project however when going to the properties of the project file – even though I changed it to Silverlight3, VS2010 did not like it and kept reverting it to a Silverlight4 project. After a few minutes of scratching my head I simply deleted Silverlight4 F# Library project and created a new F# Silverlight Library project in Silverlight3 and VS2010 was happy. Now that the project structure is set up, rest is fairly simple. You need to add the Silverlight Library as a reference to the C# Silverlight Front End. Then setup your views, since I was following the MVVM pattern I made a Views & ViewModel folder and set up the relevant View and ViewModels. The MainPageViewModel file looks as follows using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace IROAFrontEnd.ViewModels { public class MainPageViewModel : ViewModelBase { private string _iroaString; private string _inputCharacters; public string InputCharacters { get { return _inputCharacters; } set { if (_inputCharacters != value) { _inputCharacters = value; OnPropertyChanged("InputCharacters"); } } } public string IROAString { get { return _iroaString; } set { if (_iroaString != value) { _iroaString = value; OnPropertyChanged("IROAString"); } } } public ICommand MySpecialCommand { get { return new MyCommand(this); } } public class MyCommand : ICommand { readonly MainPageViewModel _myViewModel; public MyCommand(MainPageViewModel myViewModel) { _myViewModel = myViewModel; } public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { var result = ModuleMain.ConvertCharsToStrings(_myViewModel.InputCharacters); var newString = ""; foreach (var Item in result) { newString += Item + " "; } _myViewModel.IROAString = newString.Trim(); } } } } One of the features I like in Silverlight4 is the new commanding. You will notice in my I have put the code under the command execute to reference to my F# module. At the moment this could be cleaned up even more, but will suffice for now.. public void Execute(object parameter) { var result = ModuleMain.ConvertCharsToStrings(_myViewModel.InputCharacters); var newString = ""; foreach (var Item in result) { newString += Item + " "; } _myViewModel.IROAString = newString.Trim(); } I then needed to set the view up. If we have a look at the MainPageView.xaml the xaml code will look like the following…. Nothing to fancy, but battleship grey for now… take careful note of the binding of the command in the button to MySpecialCommand which was created in the ViewModel. <UserControl x:Class="IROAFrontEnd.Views.MainPageView" 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"> <Grid x:Name="LayoutRoot" Background="White"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <TextBox Grid.Row="0" Text="{Binding InputCharacters, Mode=TwoWay}"/> <Button Grid.Row="1" Command="{Binding MySpecialCommand}"> <TextBlock Text="Generate"/> </Button> <TextBlock Grid.Row="2" Text="{Binding IROAString}"/> </Grid> </UserControl> Finally in the App.xaml.cs file we need to set the View and link it to the ViewModel. private void Application_Startup(object sender, StartupEventArgs e) { var myView = new MainPageView(); var myViewModel = new MainPageViewModel(); myView.DataContext = myViewModel; this.RootVisual = myView; }   Once this is done – hey presto – it worked. I typed in some “Test Input” and clicked the generate button and the correct Radio Operators Alphabet was generated. And that’s the end of my first very basic F# Silverlight application.

    Read the article

  • WPF Dynamic Layout with ItemsControl and Grid

    - by Jason Williams
    I am creating a WPF form. One of the requirements is that it have a sector-based layout so that a control can be explicitly placed in one of the sectors/cells. I have created a tic-tac-toe example below to convey my problem: There are two types and one base type: public class XMoveViewModel : MoveViewModel { } public class OMoveViewModel : MoveViewModel { } public class MoveViewModel { public int Row { get; set; } public int Column { get; set; } } The DataContext of the form is set to an instance of: public class MainViewModel : ViewModelBase { public MainViewModel() { Moves = new ObservableCollection<MoveViewModel>() { new XMoveViewModel() { Row = 0, Column = 0 }, new OMoveViewModel() { Row = 1, Column = 0 }, new XMoveViewModel() { Row = 1, Column = 1 }, new OMoveViewModel() { Row = 0, Column = 2 }, new XMoveViewModel() { Row = 2, Column = 2} }; } public ObservableCollection<MoveViewModel> Moves { get; set; } } And finally, the XAML looks like this: <Window.Resources> <DataTemplate DataType="{x:Type vm:XMoveViewModel}"> <Image Source="XMove.png" Grid.Row="{Binding Path=Row}" Grid.Column="{Binding Path=Column}" Stretch="None" /> </DataTemplate> <DataTemplate DataType="{x:Type vm:OMoveViewModel}"> <Image Source="OMove.png" Grid.Row="{Binding Path=Row}" Grid.Column="{Binding Path=Column}" Stretch="None" /> </DataTemplate> </Window.Resources> <Grid> <ItemsControl ItemsSource="{Binding Path=Moves}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Grid ShowGridLines="True"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> </Grid> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> </Grid> What was not so obvious to me when I started was that the ItemsControl element actually wraps each item in a container, so my Grid.Row and Grid.Column bindings are ignored since the images are not directly contained within the grid. Thus, all of the images are placed in the default Row and Column (0, 0). What is happening: The desired result: So, my question is this: how can I achieve the dynamic placement of my controls in a grid? I would prefer a XAML/Data Binding/MVVM-friendly solution. Thanks.

    Read the article

  • Initialization of ComboBox in datagrid, Silverlight 4.0

    - by Budda
    I have datagrid with list of MyPlayer objects linked to ItemsSource, there are ComboBoxes inside of grid that are linked to a list of inner object, and binding works correctly: when I select one of the item then its value is pushed to data model and appropriately updated in other places, where it is used. The only problem: initial selections are not displayed in my ComboBoxes. I don't know why..? Instance of the ViewModel is assigned to view DataContext. Here is grid with ComboBoxes (grid is binded to the SquadPlayers property of ViewModel): <data:DataGrid ="True" AutoGenerateColumns="False" ItemsSource="{Binding SquadPlayers}"> <data:DataGrid.Columns> <data:DataGridTemplateColumn Header="Rig." Width="50"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <ComboBox SelectedItem="{Binding Rigid, Mode=TwoWay}" ItemsSource="{Binding IntLevels, Mode=TwoWay}"/> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> </data:DataGrid.Columns> </data:DataGrid> Here is ViewModel class ('_model_DataReceivedEvent' method is called asynchronously, when data are received from server): public class SquadViewModel : ViewModelBase<SquadModel> { public SquadViewModel() { SquadPlayers = new ObservableCollection<SquadPlayer>(); } private void _model_DataReceivedEvent(List<SostavPlayerData> allReadyPlayers) { TeamTask task = new TeamTask { Rigid = 1 }; foreach (SostavPlayerData spd in allReadyPlayers) { SquadPlayer sp = new SquadPlayer(spd, task); SquadPlayers.Add(sp); } RaisePropertyChanged("SquadPlayers"); } And here is SquadPlayer class (it's objects are binded to the grid rows): public class SquadPlayer : INotifyPropertyChanged { public SquadPlayer(SostavPlayerData spd) { _spd = spd; Rigid = 2; } public event PropertyChangedEventHandler PropertyChanged; private int _rigid; public int Rigid { get { return _rigid; } set { _rigid = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Rigid")); } } } private readonly ObservableCollection<int> _statIntLevels = new ObservableCollection<int> { 1, 2, 3, 4, 5 }; public ObservableCollection<int> IntLevels { get { return _statIntLevels; } } It is expected to have all "Rigid" comboboxes set to "2" value, but they are not selected (items are in the drop-down list, and if any value is selected it is going to ViewModel). What is wrong with this example? Any help will be welcome. Thanks.

    Read the article

  • Unable to add item to dataset in Linq to SQL

    - by Mike B
    I am having an issue adding an item to my dataset in Linq to SQL. I am using the exact same method in other tables with no problem. I suspect I know the problem but cannot find an answer (I also suspect all i really need is the right search term for Google). Please keep in mind this is a learning project (Although it is in use in a business) I have posted my code and datacontext below. What I am doing is: Create a view model (Relevant bits are shown) and a simple wpf window that allows editing of 3 properties that are bound to the category object. Category is from the datacontext. Edit works fine but add does not. If I check GetChangeSet() just before the db.submitChanges() call there are no adds, edits or deletes. I suspect an issue with the fact that a Category added without a Subcategory would be an orphan but I cannot seem to find the solution. Command code to open window: CategoryViewModel vm = new CategoryViewModel(); AddEditCategoryWindow window = new AddEditCategoryWindow(vm); window.ShowDialog(); ViewModel relevant stuff: public class CategoryViewModel : ViewModelBase { public Category category { get; set; } // Constructor used to Edit a Category public CategoryViewModel(Int16 categoryID) { db = new OITaskManagerDataContext(); category = QueryCategory(categoryID); } // Constructor used to Add a Category public CategoryViewModel() { db = new OITaskManagerDataContext(); category = new Category(); } } The code for saving changes: // Don't close window unless all controls are validated if (!vm.IsValid(this)) return; var changes = vm.db.GetChangeSet(); // DEBUG try { vm.db.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException) { vm.db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges); vm.db.SubmitChanges(); } The Xaml (Edited fror brevity): <TextBox Text="{Binding category.CatName, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding category.CatDescription, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> <CheckBox IsChecked="{Binding category.CatIsInactive, Mode=TwoWay}" /> IssCategory in the Issues table is the old, text based category. This field is no longer used and will be removed from the database as soon as this is working and pushed live.

    Read the article

  • Attaching a Command to the WP7 Application Bar.

    - by mbcrump
    One of the biggest problems that I’ve seen with people creating WP7 applications is how do you bind the application bar to a Relay Command. If your using MVVM then this is particular important. Let’s examine the code that one might add to start with.  <phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"> <shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="/icons/appbar.questionmark.rest.png" Text="About"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding DisplayAbout, Mode=OneWay}" /> </i:EventTrigger> </i:Interaction.Triggers> </shell:ApplicationBarIconButton> <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem x:Name="menuItem1" Text="MenuItem 1"></shell:ApplicationBarMenuItem> <shell:ApplicationBarMenuItem x:Name="menuItem2" Text="MenuItem 2"></shell:ApplicationBarMenuItem> </shell:ApplicationBar.MenuItems> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar> Everything looks right. But we quickly notice that we have a squiggly line under our Interaction.Triggers. The problem is that the object is not a FrameworkObject. This same code would have worked perfect if this were a normal button. OK. Point has been proved. Let’s make the ApplicationBar support Commands. So, go ahead and create a new project using MVVM Light. If you want to check out the source and work along side this tutorial then click here.  7 Easy Steps to have binding on the Application Bar using MVVM Light (I might add that you don’t have to use MVVM Light to get this functionality, I just prefer it.) 1) Download MVVM Light if you don’t already have it and install the project templates. It is available at http://mvvmlight.codeplex.com/. 2) Click File-New Project and navigate to Silverlight for Windows Phone. Make sure you use the MVVM Light (WP7) Template. 3) Now that we have our project setup and ready to go let’s download a wrapper created by Nicolas Humann here, it is called Phone7.Fx. After you download it then extract it somewhere that you can find it. This wrapper will make our application bar/menu item bindable. 4) Right click References inside your WP7 project and add the .dll file to your project. 5) In your MainPage.xaml you will need to add the proper namespace to it. Don’t forget to build your project afterwards. xmlns:Preview="clr-namespace:Phone7.Fx.Preview;assembly=Phone7.Fx.Preview" 6) Now you can add the BindableAppBar to your MainPage.xaml with a few lines of code.  <Preview:BindableApplicationBar x:Name="AppBar" BarOpacity="1.0" > <Preview:BindableApplicationBarIconButton Command="{Binding DisplayAbout}" IconUri="/icons/appbar.questionmark.rest.png" Text="About" /> <Preview:BindableApplicationBar.MenuItems> <Preview:BindableApplicationBarMenuItem Text="Settings" Command="{Binding InputBox}" /> </Preview:BindableApplicationBar.MenuItems> </Preview:BindableApplicationBar> So your final MainPage.xaml will look similar to this: NOTE: The AppBar will be located inside of the Grid using this wrapper.   <!--LayoutRoot contains the root grid where all other page content is placed--> <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <!--TitlePanel contains the name of the application and page title--> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,24,0,12"> <TextBlock x:Name="ApplicationTitle" Text="{Binding ApplicationTitle}" Style="{StaticResource PhoneTextNormalStyle}" /> <TextBlock x:Name="PageTitle" Text="{Binding PageName}" Margin="-3,-8,0,0" Style="{StaticResource PhoneTextTitle1Style}" /> </StackPanel> <!--ContentPanel - place additional content here--> <Grid x:Name="ContentGrid" Grid.Row="1"> <TextBlock Text="{Binding Welcome}" Style="{StaticResource PhoneTextNormalStyle}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="40" /> </Grid> <Preview:BindableApplicationBar x:Name="AppBar" BarOpacity="1.0" > <Preview:BindableApplicationBarIconButton Command="{Binding DisplayAbout}" IconUri="/icons/appbar.questionmark.rest.png" Text="About" /> <Preview:BindableApplicationBar.MenuItems> <Preview:BindableApplicationBarMenuItem Text="Settings" Command="{Binding InputBox}" /> </Preview:BindableApplicationBar.MenuItems> </Preview:BindableApplicationBar> </Grid> 7) Let’s go ahead and create the RelayCommands and write them up to a MessageBox by editing our MainViewModel.cs file. public class MainViewModel : ViewModelBase { public string ApplicationTitle { get { return "MVVM LIGHT"; } } public string PageName { get { return "My page:"; } } public string Welcome { get { return "Welcome to MVVM Light"; } } public RelayCommand DisplayAbout { get; private set; } public RelayCommand InputBox { get; private set; } /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { if (IsInDesignMode) { // Code runs in Blend --> create design time data. } else { DisplayAbout = new RelayCommand(() => { MessageBox.Show("About box called!"); }); InputBox = new RelayCommand(() => { MessageBox.Show("settings button called"); }); } } If you run the project now you should get something similar to this (notice the AppBar at the bottom):  Now if you hit the question mark then you will get the following MessageBox: The MenuItem works as well so for Settings: As you can see, its pretty easy to add a Command to the ApplicationBar/MenuItem. If you want to look through the full source code then click here.   Subscribe to my feed

    Read the article

  • WPF DataContext does not refresh the DataGrid using MVVM model

    - by vikram bhatia
    Project Overview I have a view which binds to a viewmodel containing 2 ObserverableCollection. The viewmodel constructor populates the first ObserverableCollection and the view datacontext is collected to bind to it through a public property called Sites. Later the 2ed ObserverableCollection is populated in the LoadOrders method and the public property LoadFraudResults is updated for binding it with datacontext. I am using WCF to pull the data from the database and its getting pulled very nicely. VIEWMODEL SOURCE class ManageFraudOrderViewModel:ViewModelBase { #region Fields private readonly ICollectionView collectionViewSites; private readonly ICollectionView collectionView; private ObservableCollection<GeneralAdminService.Website> _sites; private ObservableCollection<FraudService.OrderQueue> _LoadFraudResults; #endregion #region Properties public ObservableCollection<GeneralAdminService.Website> Sites { get { return this._sites; } } public ObservableCollection<FraudService.OrderQueue> LoadFraudResults { get { return this._LoadFraudResults;} } #endregion public ManageFraudOrderViewModel() { //Get values from wfc service model GeneralAdminService.GeneralAdminServiceClient generalAdminServiceClient = new GeneralAdminServiceClient(); GeneralAdminService.Website[] websites = generalAdminServiceClient.GetWebsites(); //Get values from wfc service model if (websites.Length > 0) { _sites = new ObservableCollection<Wqn.Administration.UI.GeneralAdminService.Website>(); foreach (GeneralAdminService.Website website in websites) { _sites.Add((Wqn.Administration.UI.GeneralAdminService.Website)website); } this.collectionViewSites= CollectionViewSource.GetDefaultView(this._sites); } generalAdminServiceClient.Close(); } public void LoadOrders(Wqn.Administration.UI.FraudService.Website website) { //Get values from wfc service model FraudServiceClient fraudServiceClient = new FraudServiceClient(); FraudService.OrderQueue[] OrderQueue = fraudServiceClient.GetFraudOrders(website); //Get values from wfc service model if (OrderQueue.Length > 0) { _LoadFraudResults = new ObservableCollection<Wqn.Administration.UI.FraudService.OrderQueue>(); foreach (FraudService.OrderQueue orderQueue in OrderQueue) { _LoadFraudResults.Add(orderQueue); } } this.collectionViewSites= CollectionViewSource.GetDefaultView(this._LoadFraudResults); fraudServiceClient.Close(); } } VIEW SOURCE public partial class OrderQueueControl : UserControl { private ManageFraudOrderViewModel manageFraudOrderViewModel ; private OrderQueue orderQueue; private ButtonAction ButtonAction; private DispatcherTimer dispatcherTimer; public OrderQueueControl() { LoadOrderQueueForm(); } #region LoadOrderQueueForm private void LoadOrderQueueForm() { //for binding the first observablecollection manageFraudOrderViewModel = new ManageFraudOrderViewModel(); this.DataContext = manageFraudOrderViewModel; } #endregion private void cmbWebsite_SelectionChanged(object sender, SelectionChangedEventArgs e) { BindItemsSource(); } #region BindItemsSource private void BindItemsSource() { using (OverrideCursor cursor = new OverrideCursor(Cursors.Wait)) { if (!string.IsNullOrEmpty(Convert.ToString(cmbWebsite.SelectedItem))) { Wqn.Administration.UI.FraudService.Website website = (Wqn.Administration.UI.FraudService.Website)Enum.Parse(typeof(Wqn.Administration.UI.FraudService.Website),cmbWebsite.SelectedItem.ToString()); //for binding the second observablecollection******* manageFraudOrderViewModel.LoadOrders(website); this.DataContext = manageFraudOrderViewModel; //for binding the second observablecollection******* } } } #endregion } XAML ComboBox x:Name="cmbWebsite" ItemsSource="{Binding Sites}" Margin="5" Width="100" Height="25" SelectionChanged="cmbWebsite_SelectionChanged" DataGrid ItemsSource ={Binding Path = LoadFraudResults} PROBLEM AREA: When I call the LoadOrderQueueForm to bind the first observablecollection and later BindItemsSource to bind 2ed observable collection, everything works fine and no problem for the first time binding. But, when I call BindItemsSource again to repopulate the obseravablecollection based on changed selected combo value via cmbWebsite_SelectionChanged, the observalblecollection gets populated with new value and LoadFraudResults property in viewmodule is populated with new values; but when i call the datacontext to rebind the datagrid,the datagrid does not reflect the changed values. In other words the datagrid doesnot get changed when the datacontext is called the 2ed time in BindItemsSource method of the view. manageFraudOrderViewModel.LoadOrders(website); this.DataContext = manageFraudOrderViewModel; manageFraudOrderViewModel values are correct but the datagrid is not relected with changed values. Please help as I am stuck with this thing for past 2 days and the deadline is approaching near. Thanks in advance

    Read the article

  • How can I bind the nested viewmodels to properties of a control

    - by Robert
    I used Microsoft's Chart Control of the WPF toolkit to write my own chart control. I blogged about it here. My Chart control stacks the yaxes in the chart on top of each other. As you can read in the article this all works quite well. Now I want to create a viewmodel that controls the data and axes in the chart. So far I'm able to add axes to the chart and show them in the chart. But I have a problem when I try to add the lineseries because it has one DependentAxis and one InDependentAxis property. I don't know how to assign the proper xAxis and yAxis controls to it. Below you see part of the LineSeriesViewModel. It has a nested XAxisViewModel and YAxisViewModel property. public class LineSeriesViewModel : ViewModelBase, IChartComponent { XAxisViewModel _xAxis; public XAxisViewModel XAxis { get { return _xAxis; } set { _xAxis = value; RaisePropertyChanged(() => XAxis); } } //The YAxis Property look the same } The viewmodels all have their own datatemplate. The xaml code looks like this: <UserControl.Resources> <DataTemplate x:Key="xAxisTemplate" DataType="{x:Type l:YAxisViewModel}"> <chart:LinearAxis x:Name="yAxis" Orientation="Y" Location="Left" Minimum="0" Maximum="10" IsHitTestVisible="False" Width="50" /> </DataTemplate> <DataTemplate x:Key="yAxisTemplate" DataType="{x:Type l:XAxisViewModel}"> <chart:LinearAxis x:Name="xAxis" Orientation="X" Location="Bottom" Minimum="0" Maximum="100" IsHitTestVisible="False" Height="50" /> </DataTemplate> <DataTemplate DataType="{x:Type l:LineSeriesViewModel}"> <!--Binding doesn't work on the Dependent and IndependentAxis! --> <!--YAxis XAxis and Series are properties of the LineSeriesViewModel --> <l:FastLineSeries DependentAxis="{Binding Path=YAxis}" IndependentAxis="{Binding Path=XAxis}" ItemsSource="{Binding Path=Series}"/> </DataTemplate> <Style TargetType="ItemsControl"> <Setter Property="ItemsPanel"> <Setter.Value> <ItemsPanelTemplate> <!--My stacked chart control --> <l:StackedPanel x:Name="stackedPanel" Width="Auto" Height="Auto" Background="LightBlue"> </l:StackedPanel> </ItemsPanelTemplate> </Setter.Value> </Setter> </Style> </UserControl.Resources> <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ClipToBounds="True"> <!-- View is an ObservableCollection of all axes and series--> <ItemsControl x:Name="chartItems" ItemsSource="{Binding Path=View}" Focusable="False"> </ItemsControl> </Grid> This code works quite well. When I add axes they get drawn. But the DependentAxis and InDependentAxis of the lineseries control stay null, so the series doesn't get drawn. How can I bind the nested viewmodels to the properties of a control?

    Read the article

  • Refactoring multiple interfaces to a common interface using MVVM, MEF and Silverlight4

    - by Brian
    I am just learning MVVM with MEF and already see the benefits but I am a little confused about some implementation details. The app I am building has several Models that do the same with with different entities (WCF RIA Services exposing a Entity framework object) and I would like to avoid implementing a similar interface/model for each view I need and the following is what I have come up with though it currently doesn't work. The common interface has a new completed event for each model that implements the base model, this was the easiest way I could implement a common class as the compiler did not like casting from a child to the base type. The code as it currently sits compiles and runs but the is a null IModel being passed into the [ImportingConstructor] for the FaqViewModel class. I have a common interface (simplified for posting) defined as follows, this should look familiar to those who have seen Shawn Wildermuth's RIAXboxGames sample. public interface IModel { void GetItemsAsync(); event EventHandler<EntityResultsArgs<faq>> GetFaqsComplete; } A base method that implements the interface public class ModelBase : IModel { public virtual void GetItemsAsync() { } public virtual event EventHandler<EntityResultsArgs<faq>> GetFaqsComplete; protected void PerformQuery<T>(EntityQuery<T> qry, EventHandler<EntityResultsArgs<T>> evt) where T : Entity { Context.Load(qry, r => { if (evt == null) return; try { if (r.HasError) { evt(this, new EntityResultsArgs<T>(r.Error)); } else if (r.Entities.Count() > 0) { evt(this, new EntityResultsArgs<T>(r.Entities)); } } catch (Exception ex) { evt(this, new EntityResultsArgs<T>(ex)); } }, null); } private DomainContext _domainContext; protected DomainContext Context { get { if (_domainContext == null) { _domainContext = new DomainContext(); _domainContext.PropertyChanged += DomainContext_PropertyChanged; } return _domainContext; } } void DomainContext_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { switch (e.PropertyName) { case "IsLoading": AppMessages.IsBusyMessage.Send(_domainContext.IsLoading); break; case "IsSubmitting": AppMessages.IsBusyMessage.Send(_domainContext.IsSubmitting); break; } } } A model that implements the base model [Export(ViewModelTypes.FaqViewModel, typeof(IModel))] public class FaqModel : ModelBase { public override void GetItemsAsync() { PerformQuery(Context.GetFaqsQuery(), GetFaqsComplete); } public override event EventHandler<EntityResultsArgs<faq>> GetFaqsComplete; } A view model [PartCreationPolicy(CreationPolicy.NonShared)] [Export(ViewModelTypes.FaqViewModel)] public class FaqViewModel : MyViewModelBase { private readonly IModel _model; [ImportingConstructor] public FaqViewModel(IModel model) { _model = model; _model.GetFaqsComplete += Model_GetFaqsComplete; _model.GetItemsAsync(); // Load FAQS on creation } private IEnumerable<faq> _faqs; public IEnumerable<faq> Faqs { get { return _faqs; } private set { if (value == _faqs) return; _faqs = value; RaisePropertyChanged("Faqs"); } } private faq _currentFaq; public faq CurrentFaq { get { return _currentFaq; } set { if (value == _currentFaq) return; _currentFaq = value; RaisePropertyChanged("CurrentFaq"); } } public void GetFaqsAsync() { _model.GetItemsAsync(); } void Model_GetFaqsComplete(object sender, EntityResultsArgs<faq> e) { if (e.Error != null) { ErrorMessage = e.Error.Message; } else { Faqs = e.Results; } } } And then finally the Silverlight view itself public partial class FrequentlyAskedQuestions { public FrequentlyAskedQuestions() { InitializeComponent(); if (!ViewModelBase.IsInDesignModeStatic) { // Use MEF To load the View Model CompositionInitializer.SatisfyImports(this); } } [Import(ViewModelTypes.FaqViewModel)] public object ViewModel { set { DataContext = value; } } }

    Read the article

  • Dynamic Scoped Resources in WPF/XAML?

    - by firoso
    I have 2 Xaml files, one containing a DataTemplate which has a resource definition for an Image brush, and the other containing a content control which presents this DataTemplate. The data template is bound to a view model class. Everything seems to work EXCEPT the ImageBrush resource, which just shows up white... Any ideas? File 1: DataTemplate for ViewModel <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:SEL.MfgTestDev.ESS.ViewModel" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <DataTemplate DataType="{x:Type vm:PresenterViewModel}"> <DataTemplate.Resources> <ImageBrush x:Key="PresenterTitleBarFillBrush" TileMode="Tile" Viewbox="{Binding Path=FillBrushDimensions, Mode=Default}" ViewboxUnits="Absolute" Viewport="{Binding Path=FillBrushPatternSize, Mode=Default}" ViewportUnits="Absolute" ImageSource="{Binding Path=FillImage, Mode=Default}"/> </DataTemplate.Resources> <Grid d:DesignWidth="1440" d:DesignHeight="900"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="192"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="120"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <DockPanel HorizontalAlignment="Stretch" Width="Auto" LastChildFill="True" Background="{x:Null}" Grid.ColumnSpan="2"> <Image Source="{Binding Path=ImageSource, Mode=Default}"/> <Rectangle Fill="{DynamicResource PresenterTitleBarFillBrush}"/> </DockPanel> </Grid> </DataTemplate> </ResourceDictionary> File 2: Main Window Class which instanciates the DataTemplate Via it's view model. <Window x:Class="SEL.MfgTestDev.ESS.ESSMainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:SEL.MfgTestDev.ESS.ViewModel" Title="ESS Control Window" Height="900" Width="1440" WindowState="Maximized" WindowStyle="None" ResizeMode="NoResize" DataContext="{Binding}"> <Window.Resources> <ResourceDictionary Source="PresenterViewModel.xaml" /> </Window.Resources> <ContentControl> <ContentControl.Content> <vm:PresenterViewModel ImageSource="XAMLResources\SEL25YearsTitleBar.bmp" FillImage="XAMLResources\SEL25YearsFillPattern.bmp" FillBrushDimensions="0,0,5,110" FillBrushPatternSize="0,0,5,120"/> </ContentControl.Content> </ContentControl> </Window> And for the sake of completeness! The CodeBehind for the View Model using System; using System.Collections.Generic; 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.Shapes; namespace SEL.MfgTestDev.ESS.ViewModel { public class PresenterViewModel : ViewModelBase { public PresenterViewModel() { } //DataBindings private ImageSource _imageSource; public ImageSource ImageSource { get { return _imageSource; } set { if (_imageSource != value) { _imageSource = value; OnPropertyChanged("ImageSource"); } } } private Rect _fillBrushPatternSize; public Rect FillBrushPatternSize { get { return _fillBrushPatternSize; } set { if (_fillBrushPatternSize != value) { _fillBrushPatternSize = value; OnPropertyChanged("FillBrushPatternSize"); } } } private Rect _fillBrushDimensions; public Rect FillBrushDimensions { get { return _fillBrushDimensions; } set { if (_fillBrushDimensions != value) { _fillBrushDimensions = value; OnPropertyChanged("FillBrushDimensions"); } } } private ImageSource _fillImage; public ImageSource FillImage { get { return _fillImage; } set { if (_fillImage != value) { _fillImage = value; OnPropertyChanged("FillImage"); } } } } }

    Read the article

  • CodePlex Daily Summary for Saturday, October 12, 2013

    CodePlex Daily Summary for Saturday, October 12, 2013Popular ReleasesTerrariViewer: TerrariViewer v7 [Terraria Inventory Editor]: This is a complete overhaul but has the same core style. I hope you enjoy it. This version is compatible with 1.2.0.3 Please send issues to my Twitter or https://github.com/TJChap2840WDTVHubGen - Adds Metadata, thumbnails and subtitles to WDTV Live Hubs: WDTVHubGen.v2.1.6.maint: I think this covers all of the issues. new additions: fixed the thumbnail problem for backgrounds. general clean up and error checking. need to get this put through the wringer and all feedback is welcome.Free language translator and file converter: Free Language Translator 3.4: fixe for new version look up.MoreTerra (Terraria World Viewer): MoreTerra 1.11.3: =========== =New Features= =========== New Markers added for Plantera's Bulb, Heart Fruits and Gold Cache. Markers now correctly display for the gems found in rock debris on the floor. =========== =Compatibility= =========== Fixed header changes found in Terraria 1.0.3.1C# Intellisense for Notepad++: Release v1.0.8.0: - fixed document formatting artifacts To avoid the DLLs getting locked by OS use MSI file for the installation.CS-Script for Notepad++ (C# intellisense and code execution): Release v1.0.8.0: - fixed document formatting artifacts To avoid the DLLs getting locked by OS use MSI file for the installation.Generic Unit of Work and Repositories Framework: v2.0: Async methods for Repostiories - Ivan (@ifarkas) OData Async - Ivan (@ifarkas) Glimpse MVC4 workig with MVC5 Glimpse EF6 Northwind.Repostiory Project (layer) best practices for extending the Repositories Northwind.Services Project (layer), best practices for implementing business facade Live Demo: http://longle.azurewebsites.net/Spa/Product#/list Documentation: http://blog.longle.net/2013/10/09/upgrading-to-async-with-entity-framework-mvc-odata-asyncentitysetcontroller-kendo-ui-gli...Media Companion: Media Companion MC3.581b: Fix in place for TVDB xml issue. New* Movie - General Preferences, allow saving of ignored 'The' or 'A' to end of movie title, stored in sorttitle field. * Movie - New Way for Cropping Posters. Fixed* Movie - Rename of folders/filename. caught error message. * Movie - Fixed Bug in Save Cropped image, only saving in Pre-Frodo format if Both model selected. * Movie - Fixed Cropped image didn't take zoomed ratio into effect. * Movie - Separated Folder Renaming and File Renaming fuctions durin...Ghostscript.NET: Ghostscript.NET v.1.1.1.: v.1.1.1. fixed problem in GhostscriptRasterizer and GhostscriptViewer when MediaBox contains negative llx or lly values. (problem reported by "Prasenjit Das"). added GhostscriptPngDevice, a friendly output device class with all png devices related switches. (GhostscriptPngDevice supports: png16m, pngalpha, pnggray, png256, png16, pngmono, pngmonod). added GhostscriptJpegDevice, a friendly output device class with all jpeg devices related switches. (GhostscriptJpegDevice supports: jpeg, jp...(Party) DJ Player: DJP.124.12: 124.12 (Feature implementation completed): Changed datatype of HistoryDateInfo from string to DateTime New: HistoryDateInfoConverter for the listbox Improved: HistoryDateInfoDeleter, HistoryDateInfoLoader, HistoryDateInfoAsynchronizer, HistoryItemLoader, HistoryItemsToHistoryDateInfoConverterSmartStore.NET - Free ASP.NET MVC Ecommerce Shopping Cart Solution: SmartStore.NET 1.2.0: HighlightsMulti-store support "Trusted Shops" plugins Highly improved SmartStore.biz Importer plugin Add custom HTML content to pages Performance optimization New FeaturesMulti-store-support: now multiple stores can be managed within a single application instance (e.g. for building different catalogs, brands, landing pages etc.) Added 3 new Trusted Shops plugins: Seal, Buyer Protection, Store Reviews Added Display as HTML Widget to CMS Topics (store owner now can add arbitrary HT...Fast YouTube Downloader: Youtube Downloader 2.1: Youtube Downloader 2.1NuGet: NuGet 2.7.1: Released October 07, 2013. Release notes: http://docs.nuget.org/docs/release-notes/nuget-2.7.1 Important note: After downloading the signed build of NuGet.exe, if you perform an update using the "nuget.exe update -self" command, it will revert back to the unsigned build.Mugen MVVM Toolkit: Mugen MVVM Toolkit 2.0: IntroductionMugen MVVM Toolkit makes it easier to develop Silverlight, WPF, WinRT and WP applications using the Model-View-ViewModel design pattern. The purpose of the toolkit is to provide a simple framework and set of tools for getting up to speed quickly with applications based on the MVVM design pattern. The core of Toolkit contains a navigation system, windows management system, models, validation, etc. Mugen MVVM Toolkit contains all the MVVM classes such as ViewModelBase, RelayCommand,...Office Ribbon Project (under active development): Ribbon (07. Oct. 2013): Fixed Scrollbar Bug if DropDown Button is bigger than screen Added Office 2013 Theme Fixed closing the Ribbon caused a null reference exception in the RibbonButton.Dispose if the DropDown was not created yet Fixed Memory leak fix (unhooked events after Dispose) Fixed ToolStrip Selected Text 2013 and 2007 for Blue and Standard themesGhostscript Studio: Ghostscript.Studio v.1.0.2: Ghostscript Studio is easy to use Ghostscript IDE, a tool that facilitates the use of the Ghostscript interpreter by providing you with a graphical interface for postscript editing and file conversions. Ghostscript Studio allows you to preview postscript files, edit the code and execute them in order to convert PDF documents and other formats. The program allows you to convert between PDF, Postscript, EPS, TIFF, JPG and PNG by using the Ghostscript.NET Processor. v.1.0.2. added custom -c s...Squiggle - A free open source LAN Messenger: Squiggle 3.3 Alpha: Allow using environment variables in configuration file (history db connection string, download folder location, display name, group and message) Fix for history viewer to show the correct history entries History saved with UTC timestamp This is alpha release and not recommended for use in productionVidCoder: 1.5.7 Beta: Updated HandBrake core to SVN 5819. About dialog now pulls down HandBrake version from the DLL. Added a confirmation dialog to Stop if the encode has been going on for more than 5 minutes. Fixed handling of unicode characters for input and output filenames. We now encode to UTF-8 before passing to HandBrake. Fixed a crash in the queue multiple titles dialog. Added code to rescue tool windows which get placed outside of the visible screen area.Vodigi Open Source Interactive Digital Signage: Vodigi Release 6.0: Please note that we have removed the Kinect support in the Vodigi Player for Version 6.0. We are in the process of building a separate Kinect-enabled Player that will support the next generation Kinect sensor. If you are currently using Kinect with the Vodigi Player, you should not upgrade to Version 6.0. The following enhancements and fixes are included in Vodigi 6.0. Vodigi Administrator - New Interface - Timelines that allow you play video and images on the Main Screen Vodigi Player -...Wsus Package Publisher: Release v1.3.1310.05: Enhance the "Reboot Remote Computers", by adding a timer before the reboot occure. So that remote users can save their documents and close applications. You can also add a message to be display. In 'Tools'->'Settings'-> Misc Tab, you can set a default message. Enhance the "Compare Computers against AD", by choosing OUs to include in the comparison.New Projects555984402e86: 555984402e86DropBoxClient: DropBoxClient is a .NET library for interacting with the DropBox Core API. EDB to PST Converter-Fastest Method for Exchange Data conversion: Enstella EDB to PST converter software-smart and valuable solution for instant and safe recovery and conversion of EDB file into PST file.How to build an autodialer with PHP using your MySQL database: As the title says we create an autodialer application, which can call multiple phones simultaneously, in the time we set up.HungNm Test: HungNm TestIBANTools: Strumento da riga di comando per il calcolo massivo dell'IBAN a partire da ABI, CAB, nazione e conto.KGitSvn: This is only a project I set up to test git-svn functionality. It will be deleted when my testing is complete.MailboxLogParser: MailboxLogParser works with Exchange ActiveSync mailbox logs to help support engineers debug issue.MiniScrum: MiniScrum is a small MVC based website to collect notes of what the team members have been up to since our last meeting. pescar2013-shop-purecss: Pescar shop, library PureCssSharePoint User Permission Check: A SP2010 webpart for any site of any site collection. Gives info on permissions of a user for: all folders in all docs, every item in all folders of the librarySocksOverHttp: Welcome free internet, kick away HTTP proxy filter.TypeScript component based framework for enterprise web application.: TypeScript component based framework for enterprise web application.ugsf migration (2007/2010/2013): UGSF ( UserGroup SharePoint France) Documentation and Ressources for SharePoint Migration ( 2007/2010/2013)weiqk's project: only test Windows Imaging Component(WIC) Demo App on WEC2013: A sample application to Demo the Windows Imaging Component(WIC) on WEC2013.WPTrakt: wptrakt

    Read the article

  • CodePlex Daily Summary for Sunday, November 27, 2011

    CodePlex Daily Summary for Sunday, November 27, 2011Popular ReleasesTerminals: Version 2 - Beta 4 Release: Beta 4 Refresh Build Dont forget to backup your config files BEFORE upgrading! As usual, please take time to use and abuse this release. We left logging in place, and this is a debug build so be sure to submit your logs on each bug reported, and please do report all bugs! Updated the About form to include the date and time of the build. Useful for CI builds to ensure we have the correct version "Favourites" and "History" save their expanded states after app restarts Code cleanup, secu...MiniTwitter: 1.76: MiniTwitter 1.76 ???? ?? ?????????? User Streams ???????????? User Streams ???????????、??????????????? REST ?????????? ?????????????????????????????? ??????????????????????????????Media Companion: MC 3.424b Weekly: Ensure .NET 4.0 Full Framework is installed. (Available from http://www.microsoft.com/download/en/details.aspx?id=17718) Ensure the NFO ID fix is applied when transitioning from versions prior to 3.416b. (Details here) Movie Show Resolutions... Resolved issue when reverting multiselection of movies to "-none-" Added movie rename support for subtitle files '.srt' & '.sub' Finalised code for '-1' fix - radiobutton to choose either filename or title Fixed issue with Movie Batch Wizard Fanart - ...Advanced Windows Phone Enginering Tool: WPE Downloads: This version of WPE gives you basic updating, restoring, and, erasing for your Windows Phone device.Anno 2070 Assistant: Beta v1.0 (STABLE): Anno 2070 Assistant Beta v1.0 Released! Features Included: Complete Building Layouts for Ecos, Tycoons & Techs Complete Production Chains for Ecos, Tycoons & Techs Completed Credits Screen Known Issues: Not all production chains and building layouts may be on the lists because they have not yet been discovered. However, data is still 99.9% complete. Currently the Supply & Demand, including Calculator screen are disabled until version 1.1.Minemapper: Minemapper v0.1.7: Including updated Minecraft Biome Extractor and mcmap to support the new Minecraft 1.0.0 release (new block types, etc).Visual Leak Detector for Visual C++ 2008/2010: v2.2.1: Enhancements: * strdup and _wcsdup functions support added. * Preliminary support for VS 11 added. Bugs Fixed: * Low performance after upgrading from VLD v2.1. * Memory leaks with static linking fixed (disabled calloc support). * Runtime error R6002 fixed because of wrong memory dump format. * version.h fixed in installer. * Some PVS studio warning fixed.NetSqlAzMan - .NET SQL Authorization Manager: 3.6.0.10: 3.6.0.10 22-Nov-2011 Update: Removed PreEmptive Platform integration (PreEmptive analytics) Removed all PreEmptive attributes Removed PreEmptive.dll assembly references from all projects Added first support to ADAM/AD LDS Thanks to PatBea. Work Item 9775: http://netsqlazman.codeplex.com/workitem/9775VideoLan DotNet for WinForm, WPF & Silverlight 5: VideoLan DotNet for WinForm, WPF, SL5 - 2011.11.22: The new version contains Silverlight 5 library: Vlc.DotNet.Silverlight. A sample could be tested here The new version add and correct many features : Correction : Reinitialize some variables Deprecate : Logging API, since VLC 1.2 (08/20/2011) Add subitem in LocationMedia (for Youtube videos, ...) Update Wpf sample to use Youtube videos Many others correctionsEZ-NFC: Alpha 1: THIS IS AN ALPHA RELEASE. STILL UNSTABLE AND SUBJECT TO ARCHITECTURE CHANGE What is implemented (In alpha) : ACR122L Device Mifare 1K tag Windows frontend#liveDB: liveDB 0.3.2: New featuresNew abstract storage scheme enabling future cloud support New file system structure and naming scheme for snapshots and journal files based on sequence numbers Journal files are never deleted Automatic snapshots during load or shutdown Renamed/added hooks to Model JournalRestored, SnapshotRestored Created an extensible logging facade Journal gets split into 1MB segments (configurable) Integrity checks before during load/create Commands are cloned by default before ...ReactiveMVVM: ReactiveMVVM v1.0: Example 1 property change: public class Example1 : ViewModelBase{ string _Userid; /// <summary> /// person infomation of owner. /// </summary> public string Userid { get { return _Userid; } set { this.RaiseAndSetIfChanged(x => x.Userid, ref _Userid, value, *true*); } // true, broadcast property change message. } //if the property changed to do...... this.ObservableProperty(x => x.Useid) ...IoCWrap: Initial: Initial release of the source code.Code for Rapid C# Windows Development eBook + LINQPad and Data Tools: LinqPad Custom Visualizer Version 1.0: First release of my LinqPad Custom Visualizer. It is compiled against the Any-CPU build of LINQPad v4.36.6 so it can only be used with the LINQPad Beta: v4.36.x. To install unzip to the LinqPad plugins folder.Distributed replay GUI: Distributed Replay Snapin: This is the dll for registering the snapin in mmc.FaST-LMM: FActored Spectrally Transformed Linear Mixed Models: FaSTLMM v1.03 Binaries for Windows and Linux: These files contain the files necessary to run FaSTLMM on Windows or Linux along with the license and users manual. To download FaSTLMM source code, please follow the changeset link located above to the Source Code tab. The FaSTLMM.Win.zip download contains both C++ and CSharp executable versions of FaSTLMM. No installer is required, just UnZip the file into a directory and run from there. Or put the installation directory on your path and run it from anywhere. The C++ version included r...SharePoint 2010 FBA Pack: SharePoint 2010 FBA Pack 1.2.0: Web parts are now fully customizable via html templates (Issue #323) FBA Pack is now completely localizable using resource files. Thank you David Chen for submitting the code as well as Chinese translations of the FBA Pack! The membership request web part now gives the option of having the user enter the password and removing the captcha (Issue # 447) The FBA Pack will now work in a zone that does not have FBA enabled (Another zone must have FBA enabled, and the zone must contain the me...SharePoint 2010 Education Demo Project: Release SharePoint SP1 for Education Solutions: This release includes updates to the Content Packs for SharePoint SP1. All Content Packs have been updated to install successfully under SharePoint SP1SQL Monitor - managing sql server performance: SQLMon 4.1 alpha 6: 1. improved support for schema 2. added find reference when right click on object list 3. added object rename supportBugNET Issue Tracker: BugNET 0.9.126: First stable release of version 0.9. Upgrades from 0.8 are fully supported and upgrades to future releases will also be supported. This release is now compiled against the .NET 4.0 framework and is a requirement. Because of this the web.config has significantly changed. After upgrading, you will need to configure the authentication settings for user registration and anonymous access again. Please see our installation / upgrade instructions for more details: http://wiki.bugnetproject.c...New Projectsandrewtatham.robocode: Andrew Tatham's Robocode botsClear SharePoint Lists: This project contains the tools used to clear the items from the one or more Lists.Clipboard Editor: How many times have you pasted something in Notepad and then copied the plain text again? We do it all the time to strip formatting from the clipboard. This utility lets you pick which format from the clipboard to keep.CS New Rus: ?? ????? ??????????? ??????. ??? ??? - CS New. ?? ???? ????? ?? ????? ??????????? ??? ? ?????????? ? ???????. ElfDoc: ElfDoc enables you to create word documents from templates, using open xml.HTC RUU .NET: HTC's legendary RUU goes .NET and Open Source.................. You can browse for .nbh file, not locked at current directory and, you can update your device's rom in .NET wayMobileGamePrototype: For now just a skeleton of the architecture.NopCommerce 23 Multi Store Support: NopCommerce 23 Multi Store Support novel: fetch novelOrchard Custom Shapes: Ready to use custom orchard shapes like a table shape.Philosophy Gadget: This gadget helps people associate known works of philosophy with their known authors.ReefTracker: A controller agnostic logging and reporting application for reef aquarium controllers. SQLQuery: SQL QueryWindows Phone Marketplace Viewer: Windows Phone Marketplace Viewer is a single aspx page for asp.net 3+ with no additional dependencies. It will show the top 2000 apps in one of the 3 categories: paid and free together, only paid or only free, for all the marketplace languages.

    Read the article

  • CodePlex Daily Summary for Friday, November 01, 2013

    CodePlex Daily Summary for Friday, November 01, 2013Popular ReleasesFamily Tree Analyzer: Version 3.0.3.0-beta test3: Count Isle of Man as England & Wales for Census Lost Cousins text was preventing drag n drop of files Lost Cousins no Countries form wont open more than one copy Changed sort order of Lost Cousins buttons to match report which matches Lost Cousins website UK Census date verification is only applied to UK facts Counts duplicate Lost Cousins facts Added report for Lost Cousins facts but no census fact Added Census Duplicate and Census Missing Location reports BEF & AFT residence facts were coun...uComponents: uComponents v6.0.0: This release of uComponents will compile against and support the new API in Umbraco v6.1.0. What's new in uComponents v6.0.0? New features / Resolved issuesThe following workitems have been implemented and/or resolved: 14781 14805 14808 14818 14854 14827 14868 14859 14790 14853 14790 DataType Grid 14788 14810 Drag & Drop support for rows Support for 11 new datatypes (to a total of 20 datatypes): Color Picker Dropdown Checklist Enum Checboxlist Enum Dropdownl...Local History for Visual Studio: Local History - 1.0: New - Support for Visual Studio 2013SmartStore.NET - Free ASP.NET MVC Ecommerce Shopping Cart Solution: SmartStore.NET 1.2.1: New FeaturesAdded option Limit to current basket subtotal to HadSpentAmount discount rule Items in product lists can be labelled as NEW for a configurable period of time Product templates can optionally display a discount sign when discounts were applied Added the ability to set multiple favicons depending on stores and/or themes Plugin management: multiple plugins can now be (un)installed in one go Added a field for the HTML body id to store entity (Developer) New property 'Extra...Community Forums NNTP bridge: Community Forums NNTP Bridge V54 (LiveConnect): This is the first release which can be used with the new LiveConnect authentication. Fixes the problem that the authentication will not work after 1 hour. Also a logfile will now be stored in "%AppData%\Community\CommunityForumsNNTPServer". If you have any problems please feel free to sent me the file "LogFile.txt".WPF Extended DataGrid: WPF Extended DataGrid 2.0.0.9 binaries: Fixed issue with ICollectionView containg null values (AutoFilter issue)Community TFS Build Extensions: October 2013: The October 2013 release contains Scripts - a new addition to our delivery. These are a growing library of PowerShell scripts to use with VS2013. See our documentation for more on scripting. VS2010 Activities(target .NET 4.0) VS2012 Activities (target .NET 4.5) VS2013 Activities (target .NET 4.5.1) Community TFS Build Manager VS2012 Community TFS Build Manager VS2013 The Community TFS Build Managers for VS2010, 2012 and 2013 can also be found in the Visual Studio Gallery where upda...SuperSocket, an extensible socket server framework: SuperSocket 1.6 stable: Changes included in this release: Process level isolation SuperSocket ServerManager (include server and client) Connect to client from server side initiatively Client certificate validation New configuration attributes "textEncoding", "defaultCulture", and "storeLocation" (certificate node) Many bug fixes http://docs.supersocket.net/v1-6/en-US/New-Features-and-Breaking-ChangesBarbaTunnel: BarbaTunnel 8.1: Check Version History for more information about this release.Collections2: Collections2 v.1.1: Collection2 v.1.1 is the 1st developer and user release of the Collections2 library. The library contains 3 classes TwoWayDictionary<S,T>, TwoWayDictionary<T>, and TwoWayDictException. Binaries are available for .NET 2.0-3.5 (Binary Collections2NET2.0 v.1.1.1.1) and .NET 4.0 (Binary Collections2NET4 v.1.1.1.1). Also available are a source code zip file (Source Collections2NET4 v.1.1.1.1.zip) containing a solution file, and, example console and library project files for Visual Studio 2010. ...Mugen MVVM Toolkit: Mugen MVVM Toolkit 2.1: v 2.1 Added the 'Should' class instead of the 'Validate' class. The 'Validate' class is now obsolete. Added 'Toolkit.Annotations' to support the Mugen MVVM Toolkit ReSharper plugin. Updated JetBrains annotations within the project. Added the 'GlobalSettings.DefaultActivationPolicy' property to represent the default activation policy. Removed the 'GetSettings' method from the 'ViewModelBase' class. Instead of it, the 'GlobalSettings.DefaultViewModelSettings' property is used. Updated...NAudio: NAudio 1.7: full release notes available at http://mark-dot-net.blogspot.co.uk/2013/10/naudio-17-release-notes.htmlDirectX Tool Kit: October 2013: October 28, 2013 Updated for Visual Studio 2013 and Windows 8.1 SDK RTM Added DGSLEffect, DGSLEffectFactory, VertexPositionNormalTangentColorTexture, and VertexPositionNormalTangentColorTextureSkinning Model loading and effect factories support loading skinned models MakeSpriteFont now has a smooth vs. sharp antialiasing option: /sharp Model loading from CMOs now handles UV transforms for texture coordinates A number of small fixes for EffectFactory Minor code and project cleanup ...ExtJS based ASP.NET Controls: FineUI v4.0beta1: +2013-10-28 v4.0 beta1 +?????Collapsed???????????????。 -????:window/group_panel.aspx??,???????,???????,?????????。 +??????SelectedNodeIDArray???????????????。 -????:tree/checkbox/tree_checkall.aspx??,?????,?????,????????????。 -??TimerPicker???????(????、????ing)。 -??????????????????????(???)。 -?????????????,??type=text/css(??~`)。 -MsgTarget???MessageTarget,???None。 -FormOffsetRight?????20px??5px。 -?Web.config?PageManager??FormLabelAlign???。 -ToolbarPosition??Left/Right。 -??Web.conf...CODE Framework: 4.0.31028.0: See change notes in the documentation section for details on what's new. Note: If you download the class reference help file with, you have to right-click the file, pick "Properties", and then unblock the file, as many browsers flag the file as blocked during download (for security reasons) and thus hides all content.VidCoder: 1.5.10 Beta: Broke out all the encoder-specific passthrough options into their own dropdown. This should make what they do a bit more clear and clean up the codec list a bit. Updated HandBrake core to SVN 5855.Indent Guides for Visual Studio: Indent Guides v14: ImportantThis release has a separate download for Visual Studio 2010. The first link is for VS 2012 and later. Version History Changed in v14 Improved performance when scrolling and editing Fixed potential crash when Resharper is installed Fixed highlight of guides split around pragmas in C++/C# Restored VS 2010 support as a separate download Changed in v13 Added page width guide lines Added guide highlighting options Fixed guides appearing over collapsed blocks Fixed guides not...ASP.net MVC Awesome - jQuery Ajax Helpers: 3.5.3 (mvc5): version 3.5.3 - support for mvc5 version 3.5.2 - fix for setting single value to multivalue controls - datepicker min max date offset fix - html encoding for keys fix - enable Column.ClientFormatFunc to be a function call that will return a function version 3.5.1 ========================== - fixed html attributes rendering - fixed loading animation rendering - css improvements version 3.5 ========================== - autosize for all popups ( can be turned off by calling in js...Media Companion: Media Companion MC3.585b: IMDB plot scraping Fixed. New* Movie - Rename Folder using Movie Set, option to move ignored articles to end of Movie Set, only for folder renaming. Fixed* Media Companion - Fixed if using profiles, config files would blown up in size due to some settings duplicating. * Ignore Article of An was cutting of last character of movie title. * If Rescraping title, sort title changed depending on 'Move article to end of Sort Title' setting. * Movie - If changing Poster source order, list would beco...Custom Controls for TFS Work Item Tracking: 1.2.0.0: This is a maintenance release that adds support for TFS 2013. The control pack contains the following work item custom controls: MultiValueControl: a ComboBox to accept and show multiple values for a field by showing a list of checkboxes. More details here: MultiValue Control ScreenshotControl: a simple control (button) to capture a screenshot as a work item attachment. More details here: Screenshot controls. AttachmentsControl: this control cab be used as an alternative to the standar...New Projects3DChemFold: TODOAcc Oct2013 Liq2 MVC3EF5: Proyecto hecho en mvc3 con Entity Framework 5 para liquidación de sueldosAssociated List Box Control: A server side control combining list boxes and buttons to move items between lists. This has custom list boxes developed from a user control in ASP.Net website.AutoSPCUInstaller: Install the SharePoint Cumulative Update without pain. Use the AutoSPCUInstaller for a clean an easy installation process.Catalano Secure Delete: Delete your privacy data permanently.Duplica: Duplica is console (Command Prompt) tool aimed to duplicate existing file into a desired destination.High performance xll add-ins for Excel: A modern C++ interface to the Microsoft Excel SDK.Home Server SMART Classic: Home Server SMART is a hard disk and SSD health monitoring, reporting and alerting tool for Windows Home Server.Message Locked Encryption Library for .NET: A MLE (Message Locked Encryption) library developed for the .NET FrameworkMuServer: Web server mainly for streaming media to web browsing capable devices.MVA: Code examples from the book Programming in C# Exam Ref 70-483.NETCommon: This is only common library for NETonioncry: onion makes the aliens cry :(sfast: cms、??????、??????SPWrap - TileBoard Webpart: SPWrap Suite: Contains web parts that are wrapping existing libraries and features into reusable & fully configurable SharePoint components.TFS Build Launcher: A single command line utility to launch your TFS builds, allowing you to pass values into build process parameters.UsefulTools: A collection of useful extension methods and utility classes for .NET in general and WPFVirtual Book Libreria Online: Proyecto Libreria entity frame 5.0XML File Editor: XML Editor

    Read the article

  • CodePlex Daily Summary for Thursday, October 10, 2013

    CodePlex Daily Summary for Thursday, October 10, 2013Popular ReleasesDynamics AX 2012 R2 Kitting: First Beta release of Kitting: First Beta release of Kitting Install by using XPO or Models.C# Intellisense for Notepad++: Release v1.0.8.0: - fixed document formatting artifacts To avoid the DLLs getting locked by OS use MSI file for the installation.CS-Script for Notepad++ (C# intellisense and code execution): Release v1.0.8.0: - fixed document formatting artifacts To avoid the DLLs getting locked by OS use MSI file for the installation.Generic Unit of Work and Repositories Framework: v2.0: Async methods for Repostiories - Ivan (@ifarkas) OData Async - Ivan (@ifarkas) Glimpse MVC4 workig with MVC5 Glimpse EF6 Northwind.Repostiory Project (layer) best practices for extending the Repositories Northwind.Services Project (layer), best practices for implementing business facade Live Demo: http://longle.azurewebsites.net/Spa/Product#/list Documentation: http://blog.longle.net/2013/10/09/upgrading-to-async-with-entity-framework-mvc-odata-asyncentitysetcontroller-kendo-ui-gli...Media Companion: Media Companion MC3.581b: Fix in place for TVDB xml issue. New* Movie - General Preferences, allow saving of ignored 'The' or 'A' to end of movie title, stored in sorttitle field. * Movie - New Way for Cropping Posters. Fixed* Movie - Rename of folders/filename. caught error message. * Movie - Fixed Bug in Save Cropped image, only saving in Pre-Frodo format if Both model selected. * Movie - Fixed Cropped image didn't take zoomed ratio into effect. * Movie - Separated Folder Renaming and File Renaming fuctions durin...Ghostscript.NET: Ghostscript.NET v.1.1.1.: v.1.1.1. fixed problem in GhostscriptRasterizer and GhostscriptViewer when MediaBox contains negative llx or lly values. (problem reported by "Prasenjit Das"). added GhostscriptPngDevice, a friendly output device class with all png devices related switches. (GhostscriptPngDevice supports: png16m, pngalpha, pnggray, png256, png16, pngmono, pngmonod). added GhostscriptJpegDevice, a friendly output device class with all jpeg devices related switches. (GhostscriptJpegDevice supports: jpeg, jp...xFunc: xFunc 2.7.3: Fixed memory leak. Small fixes.SmartStore.NET - Free ASP.NET MVC Ecommerce Shopping Cart Solution: SmartStore.NET 1.2.0: HighlightsMulti-store support "Trusted Shops" plugins Highly improved SmartStore.biz Importer plugin Add custom HTML content to pages Performance optimization New FeaturesMulti-store-support: now multiple stores can be managed within a single application instance (e.g. for building different catalogs, brands, landing pages etc.) Added 3 new Trusted Shops plugins: Seal, Buyer Protection, Store Reviews Added Display as HTML Widget to CMS Topics (store owner now can add arbitrary HT...AD ACL Scanner: 1.3: New features:Effective rights, select a security principal and match it agains the permissions in AD. Color coded permissions based on criticality when using effective rights scan. Search levels : Base, One Level, Subtree. List you domains and select one from the list. Get the size of the security descriptor (bytes). Rerporting on disabled inheritance . Better search functianlity; you can use wildcards on Trustee. Get all inherited permissions in report.MoreTerra (Terraria World Viewer): MoreTerra 1.11.2: Release 1.11.2 Full 1.2 Support =========== =Bug Fixes= =========== We have all markers solsund made sure the tile and background colors are correct. (map looks correct with no missing pink) Added better error tracking for those having trouble.Fast YouTube Downloader: Youtube Downloader 2.1: Youtube Downloader 2.1NuGet: NuGet 2.7.1: Released October 07, 2013. Release notes: http://docs.nuget.org/docs/release-notes/nuget-2.7.1 Important note: After downloading the signed build of NuGet.exe, if you perform an update using the "nuget.exe update -self" command, it will revert back to the unsigned build.Mugen MVVM Toolkit: Mugen MVVM Toolkit 2.0: IntroductionMugen MVVM Toolkit makes it easier to develop Silverlight, WPF, WinRT and WP applications using the Model-View-ViewModel design pattern. The purpose of the toolkit is to provide a simple framework and set of tools for getting up to speed quickly with applications based on the MVVM design pattern. The core of Toolkit contains a navigation system, windows management system, models, validation, etc. Mugen MVVM Toolkit contains all the MVVM classes such as ViewModelBase, RelayCommand,...Office Ribbon Project (under active development): Ribbon (07. Oct. 2013): Fixed Scrollbar Bug if DropDown Button is bigger than screen Added Office 2013 Theme Fixed closing the Ribbon caused a null reference exception in the RibbonButton.Dispose if the DropDown was not created yet Fixed Memory leak fix (unhooked events after Dispose) Fixed ToolStrip Selected Text 2013 and 2007 for Blue and Standard themesGhostscript Studio: Ghostscript.Studio v.1.0.2: Ghostscript Studio is easy to use Ghostscript IDE, a tool that facilitates the use of the Ghostscript interpreter by providing you with a graphical interface for postscript editing and file conversions. Ghostscript Studio allows you to preview postscript files, edit the code and execute them in order to convert PDF documents and other formats. The program allows you to convert between PDF, Postscript, EPS, TIFF, JPG and PNG by using the Ghostscript.NET Processor. v.1.0.2. added custom -c s...cmdradio: v0.1.1 binary: Default download in win32. For other OS see here. This is alpha version. Please report all bugs.Squiggle - A free open source LAN Messenger: Squiggle 3.3 Alpha: Allow using environment variables in configuration file (history db connection string, download folder location, display name, group and message) Fix for history viewer to show the correct history entries History saved with UTC timestamp This is alpha release and not recommended for use in productionVidCoder: 1.5.7 Beta: Updated HandBrake core to SVN 4819. About dialog now pulls down HandBrake version from the DLL. Added a confirmation dialog to Stop if the encode has been going on for more than 5 minutes. Fixed handling of unicode characters for input and output filenames. We now encode to UTF-8 before passing to HandBrake. Fixed a crash in the queue multiple titles dialog. Added code to rescue tool windows which get placed outside of the visible screen area.Wsus Package Publisher: Release v1.3.1310.05: Enhance the "Reboot Remote Computers", by adding a timer before the reboot occure. So that remote users can save their documents and close applications. You can also add a message to be display. In 'Tools'->'Settings'-> Misc Tab, you can set a default message. Enhance the "Compare Computers against AD", by choosing OUs to include in the comparison.VG-Ripper & PG-Ripper: PG-Ripper 1.4.19: NEW: Added Option to login as Guest NEW: Added Menu Option to delete an Forum Account NEW: Added Support for "ImageTeam.org links FIXED: Fixed Ripping of http://forum.babeunion.com ForumsNew ProjectsAphid: Aphid is an embeddable, cross-platform, multi-paradigm, and highly interoperable .NET scripting language.CCSP: De online plek voor de V-ICT-OR CCSP communityCLOSED: CLOSEDCorporation Wars: Corporation WarsEntityFramework.BulkInsert: Bulk insert extension for EntityFramework 5. Can be used with Code First approach only.HelpersLib: Simple set of helper libs to aid you with DVLUP challenges or general WP improvementsID3 Algorithm: ID3 algorithm from Machine Learning field. ID3 was implemented in .NET 4.0 using WinForms and C#.Impacta - C# - módulo II: Roteiro de aula para o módulo II de C# da Impacta.InstaSharp: InstaSharp is a C# library that wraps the Instagram API and makes it easy to write applications with Instagram data.iRateMyApp: Project Title iRateMyApp Project Description This is a project for Assignment 2 of Web Scripting and Content Creation (University of Hertfordshire) The projeiRateMyApps: This is a project for Assignment 2 of Web Scripting and Content Creation (University of Hertfordshire)MapLite: Android Tile Map, fork from osmdroidMileage Demo: This is a quick tool to help keep track of your mileage and translate the results to multiple output formats.multiples3and5: Small projectNido Framework with .Net 4.0 and Entity Framework help you standardize your BLL.: Nido is a reusable generic code library developed using .NET/ C# (4.0, EF) providing a common platform (Web, Windows Form, Web Service, Services and Libraries).pgist: gist, GitHubpsi56: ??ERPSharePoint QB Rating App: QB Rating App is a SharePoint 2013 App that calculates a QB's NFL and NCAA passing efficiency ratings.TFS PS Integration Editor: TFS PS Integration Editor is a tool that manage the main functionally of "TfsAdmin ProjectServer" command line tool.Tfs Test: A test TFS project.Windows Service Manager: The Service Manager is management of “Services”, wither these services are local (instance) or remote. Features 1. Start, Stop and Restart service. Work Smart: Work Smart helps prevent computer related health issues.XcbWeiXin: haha

    Read the article

< Previous Page | 1 2 3  | Next Page >