David Sandor

Build succeeded.

Visual Studio 2012 Look and Feel

clock June 15, 2012 19:49 by author dsandor

My first impression so far has been "Oh my Metro".  I am not sure if I like it yet.

image

The menus are in all CAPS.  WHY IS THE IDE YELLING AT ME?

image

The color scheme is a bit washed out.  I am still trying to get used to this but it does telegraph to the code and designer as they are where your eyes go.  I could get in to this high contrast look if it were to splash color at the portion of the UI I were currently using.

WPF Control / Element selection works well and very fast.

image

The UI is very responsive.  If you remember Visual Studio 2008 (Ugh I still have to work in VS2008) clicking on a UI element in the designer renders properties in about a minute if you are lucky (and have ReSharper disabled).  Visual Studio 2012's new IDE is very responsive.  Thank you!

image

Visual Studio 2012 adds List as an option for your DataSources if you are a drag and drop binding kinda guy.

image

The XAML Designer has some Blend functionality built right in now.  From the left: Zoom Level, Toggle Effects, Show Snap Grid,  Snap to Grid Lines, Snap to Snaplines, Show Annotations.

Toggle Effects

This allows you to turn off the special effects bound to controls.  This helps speed up the designer a great deal.

Annotations

Allows you to view annotations about your WPF application (presumably from a sketchflow annotation).

image

The Solution Explorer looks Metrofied and adds a really useful Collapse All command and a Pending Changes filter command.



Resize Images in a batch in C#/WPF with an MVVM application.

clock January 21, 2012 19:11 by author dsandor

I am working on a project where I need to resize a bunch of raster images from miscellaneous sizes to fit within a certain frame.  More specifically, I need a bunch of icons for an iPhone application and I need them to fit within a 64px by 64px frame.  I found a bunch of Photo Shop scripts, some console apps, and a few spamware solutions.  I figured half an hour and I would have one that works well.  I was right.

image

So here is how the app works:

Drag and drop the graphics files you wish to resize into the application.  The files will show in the list view area.  Next, enter the Max Height and Max Width values and then click the Resize button.

The application will write the resized file next to your original with _MaxHeightxMaxWidth appended to the filename.  Original files are not modified in any way during this process. 

So if you found this blog post in hopes that you would find a quick and simple image resizer for free, here is the link to the binaries: 

A little about the application source code.  The application is a .NET 4.0 WPF application that follows the M-V-VM (MVVM) design pattern.  Since there is drag and drop support in the application there is a little code behind to support this.  The rest of the application follow the MVVM pattern.

There is a tiny image resizer class in the project that you are free to use.  This is located in the DevSQL.Imaging assembly. 

The source code can be found below.



MVVM / WPF DelegateCommand class snippet.

clock May 19, 2011 17:16 by author dsandor

Here is the snippet I am currently using to implement a basic DelegateCommand class.

CODE:

    public class DelegateCommand : ICommand
    {
        private Action _executeMethod;
        public DelegateCommand(Action executeMethod)
        {
            _executeMethod = executeMethod;
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public event EventHandler CanExecuteChanged;
        public void Execute(object parameter)
        {
            _executeMethod.Invoke();
        }
    }

Snippet file:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>delegate command</Title>
			<Shortcut>delcom</Shortcut>
			<Description>Creates basic delegate command class for MVVM / WPF.</Description>
			<Author>DevSQL, LLC (David Sandor)</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>namespace</ID>
					<ToolTip>Namespace</ToolTip>
					<Default>ViewModel</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
namespace $namespace$
{
    public class DelegateCommand : ICommand
    {
        private Action _executeMethod;
        public DelegateCommand(Action executeMethod)
        {
            _executeMethod = executeMethod;
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public event EventHandler CanExecuteChanged;
        public void Execute(object parameter)
        {
            _executeMethod.Invoke();
        }
    }
}
$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>



RFID Client for Spares Management

clock May 10, 2011 11:01 by author dsandor

Business Problem

Large companies have lots of facilities which need spare part inventory on hand.  Facility operators may not reorder parts in a timely fashion which can lead to a local shortage of equipment.  Some facilities may hoard equipment creating a local surplus of equipment.  Both extremes are costly to a company.

Solution

Provide a simple to use touch screen computer that detects when a part is leaving or entering the spare parts room.  Upon detection of the part the touch screen computer displays a ‘tag’ with information about the part.  The facility user can touch the tag on the screen and note the use of the part.  When parts come in for replenishment the facility user can notate the put away location of the part.  When are part is used inventory levels at MDSi are updated.  If the minimum stocking level is reached a reorder is automatically generated and shipped to the facility to keep the stocking level true.

Components

RFID Client (Touch screen workstation)
This is the device with which the facility users interact.

image

The client is built with Microsoft .NET Framework 4.0 and uses Windows Presentation Foundation (WPF) to present the UX.  The client leverages the Model-View-ViewModel (MVVM) architectural pattern and is written in C#.  Communication to the home office is provided via WCF services.

image

RFID Tags are read via a Motorola XR-450 tag reader.  This reader was selected because it has a built in Windows CE operating system that allows us to write Mobile Embedded .NET applications to interact with the reader and with our WCF Services.  The RFID Client Workstation has a Windows Service written in C# and .NET 4.0 which continually polls the XR-450 reader for new tags.  The service exposes a .NET Remoting service which is consumed locally by the client UI.  Multicast events are thrown and the client system can respond to new tags accordingly.


RFID WCF Services
All RFID Clients communicate to a set of centralized web servers in an NLB farm.  The WCF Services provide a data exchange layer which provides caching by leveraging the AppFabric Cache feature of Windows Server 2008 R2.  Data is stored in a SQL 2008 R2 Cluster and the data is organized through Microsoft Dynamics AX 2009.  X++ and Business Connector code was created to interface through the ERP system and pass through all of the business rules configured in the Dyanmics Ax system.  In addition to using the .NET Business Connector and custom Dynamics Ax projects to manage the data, ADO.NET, Linq and C# is used in the creation of these services.

RFID Management Display
A Network Operation Center (NOC) application was created to provide real-time node (RFID Touch Screen Client) availability data.  This data is organized on a map and allows an operator to drill in to a workstation and remotely manage the system.

image

RFID Warehouse Printing
Tools were created to interface with the Microsoft Dynamics Ax 2009 ERP system which allow a warehouse employee to print RFID labels for items being shipped out for replenishment.  This system interfaces with the Zebra RZ 400 RFID Printer.  This application was created using WPF, WCF, MVVM.

image

RFID On-Site Inventory and Auditing Tool
This application allows a warehouse specialist to audit a sparing facility.  This application is written using WPF and .NET 4.0.  The application consumes the same WCF services provided for the RFID Client to connect to the ERP system.  The application allows a specialist to print labels via a wireless Zebra RP4T RFID Label printer.  Using this application a project coordinator can determine what inventory is needed on site and what can be returned for general usage to the Distribution Center (DC).  This allows for a quick and efficient auditing process.  The warehouse specialist does not need to know anything about the product, just scan the serial number and the application tells the specialist the disposition of the part based on the Min/Max settings in the ERP system.

image

RFID Node Creation Tool
The Node Creation Tool allows a support engineer to provision a remote RFID Touch Screen Client from a central location.  A support engineer can provision all of the standard configuration settings for Development, Test, and Production from the single tool.  This application was created with WPF, C#, WCF, MVVM.

image

RFID Online Spares Management Web Application
A Silverlight application was created to provide scaled down functionality for locations that do not have the RFID Touch Screen client installed.  Some locations need the ability to consume, count and audit their inventory without an RFID client.  In this case a laser barcode scanner is used to scan the RFID barcode.  This application was written in Silverlight 4.0, uses WCF Services, and employs the MVVM architectural pattern.

image



Enable .config file build configuration transformations in non-web based applications.

clock April 28, 2011 11:05 by author dsandor

So Web Application projects have this great new feature that allows you to use an XML Transform file to merge settings into your Web.Config file based on the build configuration.  For example, if you have a Release build configuration you might want your connectionString section to point to a production server instead of your development server.  See this link for more information on Web Config Transforms.

This is a really cool feature and it is possible to use this with non-web application projects.  You can configure your project file to support this very easily.  You do need to insert some XML into your csproj file but it is really lightweight.

First, Add an App.config file to your project if you do not already have one.

Next, close Visual Studio and open your *.csproj file in notepad.

Go to the very end of the file and insert the UsingTask and Target sections directly above the </Project> closing tag. 

  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
    <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
  <Target Name="AfterCompile" Condition="exists('app.$(Configuration).config')">
    <!-- Generate transformed app config in the intermediate directory -->
    <TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
    <!-- Force build process to use the transformed configuration file from now on. -->
    <ItemGroup>
      <AppConfigWithTargetPath Remove="app.config" />
      <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
        <TargetPath>$(TargetFileName).config</TargetPath>
      </AppConfigWithTargetPath>
    </ItemGroup>
  </Target>
</Project>

 

Now find the section that has your App.config file include.  It will likely be in a <None /> tag.  Replace that tag with the following code. (Include a App.CONFIGURATION.config file for each build configuration you use.

    <Content Include="App.config">
      <SubType>Designer</SubType>
    </Content>
    <Content Include="App.Test.config">
      <DependentUpon>App.config</DependentUpon>
    </Content>
    <Content Include="App.Release.config">
      <DependentUpon>App.config</DependentUpon>
    </Content>

Save your csproj file and open it up in Visual Studio again.

image

Now when you build your solution/project the XML Transforms in your App.CONFIGURATION.config file will be merged at build time.



Left-click context menu for WPF

clock April 28, 2011 08:52 by author dsandor

I had to build a small configuration screen for an over-the-internet printing solution for Microsoft Dynamics Ax.  The application has an image that I want the user to click with either the left or right mouse button to open the context menu.  This menu allows the user to start or stop the print engine service.

image

Left or right clicking opens the context menu.

image

Here is the XAML for the Image with Context Menu.

<Image Source="/WarehouseManagement.Service.PrintEngineUI;component/Images/service.png" Height="24" Margin="6,0,0,0"
       Name="ibtnServiceController" MouseLeftButtonUp="ibtnServiceController_MouseLeftButtonUp">
    <Image.ContextMenu>
        <ContextMenu Name="cmServiceController">
            <MenuItem Header="Start" Name="miStart" Click="miStart_Click" />
            <MenuItem Header="Stop" Name="miStop" Click="miStop_Click" />
        </ContextMenu>
    </Image.ContextMenu>
</Image>

Note: MVVM Commanding is not used here for simplicity of this post.
In this XAML snippet I named the Image and consumed the MouseLeftButtonUp event on the Image.  I also added the context menu to the Image control and named the ContextMenu.

The code behind looks like this:

private void ibtnServiceController_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    cmServiceController.PlacementTarget = (UIElement)sender;
    cmServiceController.IsOpen = true;
}

In this code, PlacementTarget indicates the UIElement that the context menu will pop out from.  In this case we just use the Image element itself as passed in to the event handler via the sender argument.

Next, you simply set IsOpen to true and the context menu will be displayed over the PlacementTarget.



Two MVVM snippets I use a lot: ViewModelBase and ModelBase

clock September 5, 2010 18:03 by author dsandor

I use these two snippets a lot for WPF and Silverlight development.  I decided to post them on the blog so that I have them available to me whenever and wherever.  I always seem to be searching through older projects for this code.

vmb

This snippet creates the ViewModelBase that I use almost everywhere.  It simply implements INotifyPropertyChanged and works in both WPF and Silverlight.  I use this for my ViewModels so that the properties on the VM are observable for databinding.  I use this in conjunction with my propsn snippet that creates a property with SafeNotify calls in the setter.

mb

This snippet is used to create the ModelBase.  Again, this is a WPF / Silverlight compatible class.  I link my model such that it compiles for WPF and Silverlight so that I can share my model between my WCF and my UI.  This class gives me INotifyPropertyChanged, SafeNotify, and a ToString implementation that uses reflection to dump a shallow representation of the class.

Hope this code helps someone.



Solved: Objects are not fully deserializing when using DataContractSerializer in Silverlight.

clock July 7, 2010 02:53 by author dsandor

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer_members.aspx

So as it turns out, your XML stream must have the XML Nodes in Alphabetical Order when trying to deserialize XML data into an object.  Very wierd.



Silverlight Hover Button – XAML Style implementation with code that is dynamic and skinnable.

clock July 6, 2010 04:52 by author dsandor

So I needed to create a hover button.  The idea is that when the mouse rolls over the button the image will flip between a normal and ‘over’ version of the button image.  This is the same thing as old school image rollover code we have all used before.  There is an image that you use for a button in the ‘normal’ or ‘off’ state and when the mouse rolls over the image the picture changes to the ‘over’ or ‘on’ state.

It is pretty easy to do this statically.  Edit the button style, slap a couple of images in the ControlTemplate and tie that to the Normal and MouseOver visual states and you are done.

But what if you want to be able to use that same style for all your buttons and you want to be able to databind the Normal and MouseOver images?

This was pretty easy with a trick here or there.

First, we need to create a HoverButton class that inherits from the standard Button.  We need to do this because we need 2 new properties for our Normal and Over image url���s.

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;
 
namespace MySLApplication.Local
{
    public class HoverButton : Button
    {
 
 
        public string NormalImageUrl
        {
            get { return (string)GetValue(NormalImageUrlProperty); }
            set { SetValue(NormalImageUrlProperty, value); }
        }
 
        public static readonly DependencyProperty NormalImageUrlProperty =
            DependencyProperty.Register("NormalImageUrl", typeof(string), typeof(HoverButton), 
            new PropertyMetadata(""));
 
 
 
        public string MouseOverImageUrl
        {
            get { return (string)GetValue(MouseOverImageUrlProperty); }
            set { SetValue(MouseOverImageUrlProperty, value); }
        }
 
        public static readonly DependencyProperty MouseOverImageUrlProperty =
            DependencyProperty.Register("MouseOverImageUrl", typeof(string), typeof(HoverButton), 
            new PropertyMetadata(""));
 
 
 
    }
}

This is the button you will place on your design surface instead of the regular button.  This one gives us NormalImageUrl and the MouseOverImageUrl.  These properties we will set to the URL for the images we want to use for our normal state and mouse over state.

Next is the Style (see the zip file at the bottom of this post for the actual code).  Since the Style is so big, I will describe the important pieces to you.

First, your XAML that contains this style code needs to have a namespace reference to the HoverButton’s namespace.  I named mine local so you will see my TargetType set to local:HoverButton.

xmlns:local="clr-namespace:MySLApplication.Local"

So the style starts out like this:

<Style x:Key="HoverButtonStyle" TargetType="local:HoverButton">
            <Setter Property="Background" Value="#FF1F3B53"/>
            <Setter Property="Foreground" Value="#FF000000"/>
            <Setter Property="Padding" Value="3"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Height" Value="36" />
            <Setter Property="Width" Value="118" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="local:HoverButton">
                        <Grid>
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">

Note the TargetType in both instances is pointed to the local namespace and the HoverButton class name.  The real magic occurs in the ControlTemplate portion of the code.  Here there are several Visual States defined.  We are concered with two of them (feel free to extend this to the others also): Normal and MouseOver.

You will notice in each of the two Visual States we are concerned with there is a storyboard.  The StroryBoard executes when the visual state is entered.  So for example, when the button starts out it is in the Normal state.  When the control is rendered the Normal visual state causes the storyboard defined here to execute:

 

<VisualState x:Name="Normal">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" 
        Storyboard.TargetName="OverImage">
            <DiscreteObjectKeyFrame KeyTime="0">
                <DiscreteObjectKeyFrame.Value>
                    <Visibility>Collapsed</Visibility>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" 
        Storyboard.TargetName="NormalImage">
            <DiscreteObjectKeyFrame KeyTime="0">
                <DiscreteObjectKeyFrame.Value>
                    <Visibility>Visible</Visibility>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

What happens here is that the StoryBoard sets the OverImage’s Visibility property to Collapsed and the NormalImage’s Visibility property to Visible. 

Before confusion sets in, scroll down to the bottom of the style.  You will see the two images we just discussed.

<ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" 
   Content="{TemplateBinding Content}" 
   HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
   Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
<Image x:Name="NormalImage" DataContext="{TemplateBinding NormalImageUrl}" Source="{Binding}" />
<Image x:Name="OverImage" DataContext="{TemplateBinding MouseOverImageUrl}" Source="{Binding}" />

The two images defined inside the button’s visual surface are the actual images you will see at runtime.  Notice that we had to set the DataContext of the Image control to the property NormalImageUrl and MouseOverImageUrl and THEN set the Source property to {Binding}.  You need this little trick in order to allow databinding to convert the string based URL to an ImageSource.

So now we are good to go.  We can use our HoverButton like this:

<local:HoverButton Content="" Height="36" HorizontalAlignment="Left" 
    Margin="508,558,0,0" x:Name="btnSpin" VerticalAlignment="Top" Width="118" 
    Click="btnSpin_Click" Style="{StaticResource HoverButtonStyle}"
    NormalImageUrl="http://yourdomain.com/Normal.png"
    MouseOverImageUrl="http://yourdomain.com/Over.png"/>

So now you can specify the Normal and MouseOver images for your button.  The same style can be used for all these hover buttons, just specify the 2 images and you are set. 

 

Download File - HoverButtonSource

 

 

 

 

 

 



Solved: Cannot resolve TargetProperty (UIElement.RenderTransform).(CompositeTransform.TranslateY) on specified object.

clock July 4, 2010 05:02 by author dsandor

I was using Blend 4 to do some simple animations then copy and pasting the storyboard for use on other objects in my application.  When I executed the Begin() method on the storyboard I would get the following:

Cannot resolve TargetProperty (UIElement.RenderTransform).(CompositeTransform.TranslateY) on specified object.

My XAML was pretty basic.  I finally noticed that Blend had populated the RenderTransform property for me on the working objects.  When I cut and pasted and updated the target object I failed to add the render transform.  Doing so fixes the problem:

Working:

<local:Tile ImageUrl="/SL;component/Images/02_100x100.png" Margin="0,200,0,0" Height="100"
 Width="100" VerticalAlignment="Top" x:Name="Tile_2"
 RenderTransformOrigin="0.5,0.5" >
   <local:Tile.RenderTransform>
        <CompositeTransform/>
   </local:Tile.RenderTransform>
</local:Tile>

Not working:

<local:Tile ImageUrl="/SL;component/Images/02_100x100.png" Margin="0,200,0,0" Height="100"
 Width="100" VerticalAlignment="Top" x:Name="Tile_2"
 RenderTransformOrigin="0.5,0.5" >
</local:Tile>
 

So if you get this message it is basically telling you that you are missing the RenderTransform property on the target object.



How To: Make a complex clipping path in Blend 4.

clock July 3, 2010 18:38 by author dsandor

This how-to will show you a few simple steps to making a clipping path in Blend 4.  Below is a mockup of my basic canvas (this is a PNG imported into Blend).  I want to make the green area visible and I want to clip the while rectangles out of the image.  Eventually, I will place some animated elements where the white rectangles are.

game-mockup

The first thing you want to do is to draw rectangles where you want the image to be visible.

image 

Now that I have all of my purple rectangles drawn out I am ready to convert them to a clipping path.

Remember, the rectangles are the areas that will be visible on the clipped object.

image

Choose the direct select tool: image and select all of your rectangles.  Hold down the CTRL key and you can multi-select.  You can also select the rectangles from the Objects and Timeline window.

image

Choose Object | Path | Convert to Path from the Blend menu.  This converts all your rectangles to a path which we will in turn convert to a clipping path.

image

Next, go back to Object | Path on the menu and choose Make Compound Path.  This will make one complex path from your individual paths.

image

Now that you have one compound path select the Path object from the Objects and Timelines window.  Now you can go back to Object | Path and you have the option to Make Clipping Path.

image

Now you choose the object to clip and you will now have a clipped object (an image in my case). 

image

Here is the end result in the Blend designer:

image

And here is the nice clean XAML you generated (please note, for space constraints I truncated the path data in the Clip property):

    <Grid x:Name="LayoutRoot" >
        <Image Margin="0" Source="Images/game-mockup.png" Stretch="Fill" 
         Clip="M0.5,0.5 L799.5,0.5 L799.5,202.5 L0.5,202.5 z M0.5,203.5 ... z">
        </Image>
    </Grid>


MockupToXaml codeplex project progression.

clock May 18, 2010 06:47 by author dsandor

The UI for the converter kind of stinks right now because I have been concentrating on functionality.  I am now rendering XAML via plug-in modules.  In addition a preview of the rendered XAML is displayed after generating the XAML.

The UI is really basic right now:

image

Click the Load Mockup button to locate a .BMML mockup file.

image

The BMML document is parsed into a set of .NET objects.  For now, the controls are displayed in a grid.  This is going to be removed.  It was mainly used while coding the Mockup XML parsing logic.

image

Clicking generate will generate the XAML in the texbox at the bottom of the form.

image

In addition to generating the XAML, it is parsed at runtime and the Mockup is compiled at runtime and previewed.

image

That is the preview of the XAML rendered from my mockup below:

image

I still need to include the properties and sample data in the Xaml controls.  But for now, we have a start.



How To: WPF Databind a URL / URI to an Image control.

clock May 12, 2010 21:59 by author dsandor

The following code creates a UriToBitmapImage value converter.  Simply reference the converter in your databinding and you will be able to data bind an Image control to a URL and have it displayed on your WPF surface.

First, the value converter code:

namespace MyApp.Local
{
    public class UriToBitmapImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
             CultureInfo culture)
        {
            BitmapImage image = new BitmapImage();
            if (value != null)
            {
                try
                {
                    image.BeginInit();
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    image.UriSource = new Uri((string)value, UriKind.Absolute);
                    image.EndInit();
                }
                catch
                {
                    image = null;
                }
            }

            return image;
        }

        public object ConvertBack(object value, Type targetType, object parameter, 
               CultureInfo culture)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }
}

Add the value converter to your project and compile.

Next, you need to reference the namespace that contains this new class on the WPF Window/Page/Control that you wish to use the converter. (You can also add your converters at the App level.)

xmlns:loc="clr-namespace:MyApp.Local"

I added the UriToBitmapImageConverter class to the MyApp.Local namespace.  Thus, I needed to add a reference to the CLR namespace in my XAML in order to use the converter.

Next, you need to add the converter to your XAML page’s resources:

   <Page.Resources>
        <loc:UriToBitmapImageConverter x:Key="UriToImageConverter" />
   </Page.Resources>

Here I used Page.Resources because I am adding this converter to a WPF Page.  It would be Window.Resources if you are working with a WPF Window or UserControl.Resources if you are adding this to a UserControl.

Now, simply data bind your image:

 

<Image Margin="8,7,4,8" 
      Source="{Binding ImageUri, Converter={StaticResource UriToImageConverter}}" 
      Stretch="Fill" d:IsHidden="False"/>

In the Source attribute I am data binding a URL / URI which is of type string.  This string is then passed through the UriToImageConverter and output is a BitmapImage object that downloads the image dynamically and displays it.

If I have some extra time, or requests, I will build a sample application to demonstrate.



Mockup to XAML – A Balsamiq Mockup to XAML conversion tool.

clock May 11, 2010 05:52 by author dsandor

Today the mockuptoxaml open source project officially kicked off.  The code and the project is not yet publicly published on Codeplex yet.  I am getting the code and the first alpha release of the application ready.  It is in its infancy.  I will post on my blog the progress of the application until it is officially available on codeplex.

Many thanks to Balsamiq for providing me with a license code free of charge.

So my baseline mockup looks like this:

image

Version 0.1 of the application :D generates this crude WPF form.  As you can see there is a lot of work to do, but it is slowly coming together.

image



Balsamiq Mockup to XAML (WPF or Silverlight)

clock May 6, 2010 23:12 by author dsandor

So I found this cool mockup tool that will export to XML a nifty screen mockup.  I have decided to spend a few hours on a converter that will let me input a mockup XML file and output a WPF or Silverlight XAML file.  Seems easy enough.

image



How to display a default value in a combo box WPF / XAML.

clock May 5, 2010 22:55 by author dsandor

This is a repost.  Someone named Tri Q in Syndey answered a question like this very elegantly.  I am reposting it in order to preserve it.

 

Here is the original question and answer.

You can do this without any code behind by using a IValueConverter.

<Grid> 
   <ComboBox 
       x:Name="comboBox1" 
       ItemsSource="{Binding MyItemSource}"  /> 
   <TextBlock 
       Visibility="{Binding SelectedItem, ElementName=comboBox1, 
                          Converter={StaticResource NullToVisibilityConverter}}" 
       IsHitTestVisible="False" 
       Text="... Select Team ..." /> 
</Grid> 

[David Sandor]

I would take this a step further and modify the ItemTemplate

<ComboBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding}" FontSize="22" FontWeight="Bold" />
<TextBlock Visibility="{Binding SelectedItem, ElementName=comboBox1,
Converter={StaticResource NullToVisibilityConverter}}" IsHitTestVisible="False" Text="... Select Team ..." /> 
    </DataTemplate></ComboBox.ItemTemplate>

Here you have the converter class that you can re-use.

public class NullToVisibilityConverter : IValueConverter 
{ 
    #region Implementation of IValueConverter 
 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        return value == null ? Visibility.Visible : Visibility.Collapsed; 
    } 
 
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        throw new NotImplementedException(); 
    } 
 
    #endregion 
} 

And finally, you need to declare your converter in a resource section.

<Converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter" /> 

Where Converters is the place you have placed the converter class. An example is:

xmlns:Converters="clr-namespace:MyProject.Resources.Converters" 

The very nice thing about this approach is no repetition of code in your code behind.



WPF Databinding visibility of a control to your ViewModel / DataContext boolean value.

clock May 5, 2010 18:57 by author dsandor

In many cases you will need to set the visibility of a control based on a value of a property of your ViewModel class.  There are several ways to accomplish this.  The most reusable manner of accomplishing this is to use a value converter to convert the boolean value to a Visibility enumerator.  It sounds complicated but it is super easy.

Note: Before I continue I would like to state that this is an example simplified in order to describe this concept.  The code in this example databinds the IsChecked property of a CheckBox to the view model then databinds that boolean property to the Visibility property of the Button control.  In XAML you can property bind the two controls but that is not what this example is about.  Instead of making this a long example with database calls and other complications I wanted to make this as simple and clear cut as can be.  So if you are looking to databind the property of one control to the property of another this is not the right article for you.

image

So to demonstrate the value converter we will DataBind the (bool) IsChecked property of the CheckBox to the (bool) IsButtonVisible property of the MainWindowViewModel class.  The Visibility property of the Button control is databound to the same (bool) IsButtonVisible property of the MainWindowViewModel class.

So the XAML for this Window looks like this:

 

<Window x:Class="ValueConverterExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ValueConverterExample.Local"
        Title="MainWindow" Height="218" Width="196">
    <Grid>
        <Grid.Resources>
            <local:BooleanVisibilityValueConverter x:Key="BoolToVisible" />
        </Grid.Resources>
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="51,110,0,0"
          Name="button1" VerticalAlignment="Top" Width="75" 
          Visibility="{Binding Path=IsButtonVisible,Converter={StaticResource BoolToVisible}}" />
        <CheckBox Content="Is Button Visible?" Height="16" HorizontalAlignment="Left"
          Margin="36,56,0,0" Name="checkBox1" VerticalAlignment="Top" 
          IsChecked="{Binding IsButtonVisible}" />
    </Grid>
</Window>

Note there is a Grid.Resources section in the XAML.  This section is making available to the controls on the Grid the BooleanVisibilityValueConverter object and is naming it BoolToVisible.  This will allow any control on this Grid to use that value converter.  In order to do this, I had to include a namespace that I called local in the Window tag declaration.  This sets up a reference to the Namespace where the Value Converter class resides.

Next, in the Button control’s XAML you see that the Visibility Property is DataBound to the IsButtonVisible property of the DataContext.  Below is the code behind for this Window:

namespace ValueConverterExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        MainWindowViewModel viewModel = new MainWindowViewModel();

        public MainWindow()
        {
            this.DataContext = viewModel;
            InitializeComponent();
        }
    }
}

And the code for the MainWindowViewModel is located below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace ValueConverterExample.ViewModel
{
    public class MainWindowViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;


        private bool _IsButtonVisible;
        public bool IsButtonVisible
        {
            get { return _IsButtonVisible; }
            set
            {
                _IsButtonVisible = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("IsButtonVisible"));
            }
        }

    }
}

As you can see the IsButtonVisible property which both the CheckBox and Button are databound is a boolean.  This is possible via the ValueConverter:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media;
using System.Windows;

namespace ValueConverterExample.Local
{
    public class BooleanVisibilityValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                if (((bool)value) == true)
                    return Visibility.Visible;
                else
                    return Visibility.Collapsed;
            }

            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {

            throw new Exception("The method or operation is not implemented.");

        }


    }
}

This value converter code will accept a Boolean value in, and spit out a Visibility enum.  The magic happens in this databinding expression for the button control’s visibility property:

Visibility="{Binding Path=IsButtonVisible,Converter={StaticResource BoolToVisible}}"

Here we are setting the binding to the IsButtonVisible property of the DataContext.  In addition we are telling the DataBinder to use the converter named BoolToVisible.  Remember we gave our BooleanVisibilityValueConverter class a key name of BoolToVisible when we defined the Grid Resources.

Attached is a sample project.  I hope this helps someone!

Download Source Code: ValueConverterExample.zip



About the author

David Sandor is a Software Architect working in Chicago, IL.  My development focuses around the Microsoft Stack including Azure, AppFabric, Silverlight, WPF, .NET Framework, and various mobile devices including iOS (iPhone/iTouch), Android, Windows Mobile and Windows Phone 7.

Month List

Sign in