Friday, December 30, 2011

WPF : Issue with red border appearing for Error elements even when parent panel is collapsed/hidden


In WPF there is an issue when you are using default error temple to show red borders around textboxes/datepickers/combo-boxes or any databound control.

Untill you have the panel visible to you everything looks okay, but moment you collapse that panel or hide it, the red boxes around those controls remain visible.
You can get away with this problem in following 2 steps

Step 1) First you need to change default error template to have only AdornedElementPlaceHolder, you don’t need any other control in error template.

Step 2) Then you need to change Trigger for “Validation.HasError” property, to mark border for control with Red color as shown below.


Wednesday, December 28, 2011

WPF Memory Leak (DataTemple)


In WPF programming, there is a well-known memory leak which occurs when you use a DataTemplate to display tabs in Tabcontrol.  

If in a tab control you are creating tabs dynamically and also generating contents of those tabs using datatemplate binding as show below
    <DataTemplate DataType="{x:Type ViewModels:SomeViewModel}" >
                <views:SomeView  />
    </DataTemplate>

Then, you are injecting a potential memory leak in your application. Because whenever your tab is highlighted WPF runtime creates a new instance if “SomeView” class and uses it.
As of now only workaround for this problem is to use a ViewFactory which will supply your views. This ViewFactory will have a static object which will create only one instance of “SomeView” class and use it through application lifetime.
So, your changed code would look like
    <DataTemplate DataType="{x:Type ViewModels:SomeViewModel}" >
        <ContentPresenter Content="{x:Static local:ViewsFactory.SomeViewInstance}" />
    </DataTemplate>

And implementation of your ViewFactory class would be something like
 public static class ViewsFactory
    {
        #region SomeViewInstance

        private static SomeView _SomeViewInstance = null;

        /// <summary>
        /// Gets or sets the  SomeViewInstance  property. 
        /// </summary>
        public static SomeView SomeViewInstance
        {
            get
            {
                if (_SomeViewInstance == null)
                {
                    _SomeViewInstance = new SomeView();
                }

                return _SomeViewInstance;
            }
        }

        #endregion
    }

Hope it helps!!!

Sunday, December 25, 2011

WPF : Setting default focus on a control when window is shown


Here is the trick to set focus on a particular control when windows is started up in WPF. It doesn’t require any code-behind.
Add FocusManager.FocusElement in Window tag as show below and bind it with the element that should receive focus when windows is started up.


Sunday, December 18, 2011

.Net ServiceHost Directives


1) For WCF Dataservice :
<%@ ServiceHost Language="C#" Factory="System.Data.Services.DataServiceHostFactory"
Service="NwdDataService" %>
Here as we can see that  BwDataService is wcf data service class which exposes Northwind database entities.
Factory property indicates DataServiceHostFactory which has logic of taking an entity and exposing its content using OData pattern.

2) For WCF service :
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>
Here we have path for code behind class file which happens to be Service.cs, this file contains definition of Service class.
Service defines name for wcf service class which has implementation of wcf service class.

3) Web Service
<%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService" %>
Here also we have location of Codebehind file and service class name which defines actual service content.

Saturday, December 17, 2011

WPF: Draw a 3D Border


The coolest technique to draw a3D border in wps is use a border element as a child element for existing border element.

1)      Create a regular border
2)      Decide on which side you want to show 3D edge
3)      Add another border as its child element, and set its as show in following code.
<Border Height="200" Width="299" BorderThickness="1,26,26,26" BorderBrush="LightBlue">
<Border Height="148" Width="270" BorderThickness="0,1,1,1" BorderBrush="Blue" />
          </Border>
its o/p would be as shown below.




Tuesday, December 13, 2011

Launching WSAT (Website Administration Tool) for a web site


1)      Open website in Visual Studio.
2)      Open “ Solution Explorer”, and Click on “ASP.Net Configuration” Icon as shown in below image


3)      It will launch WSAT as show below

Friday, December 9, 2011

WPF : Creating a Behavior for a TextBox which invokes a command when Enter key is pressed



Goal :  Execute a command when an enter key is pressed ,while focus is in a text-box.  This command can be a command bounded to a Button or any UI element.
Look at following code
Here I am going to create an attached property of ICommand type, which would be applied to TextBoxes. While that property is getting attached to a TextBox, I register an EventHandler for KeyUp event and in that I check for Enter key cod, if it matches I execute attached command property for that object.

/// <summary>
/// EnterKeyCommand Attached Dependency Property
/// </summary>
public static readonly DependencyProperty EnterKeyCommandProperty =
DependencyProperty.RegisterAttached("EnterKeyCommand"typeof(ICommand), typeof(TextBoxBehaviours), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnEnterKeyCommandChanged)));
 
/// <summary>
/// Gets the EnterKeyCommand property. This dependency property 
/// indicates ....
/// </summary>
public static ICommand GetEnterKeyCommand(DependencyObject d)
{
 return (ICommand)d.GetValue(EnterKeyCommandProperty);
}
 
/// <summary>
/// Sets the EnterKeyCommand property. This dependency property 
/// indicates ....
/// </summary>
public static void SetEnterKeyCommand(DependencyObject d, ICommand value)
{
 d.SetValue(EnterKeyCommandProperty, value);
}
 
/// <summary>
/// Handles changes to the EnterKeyCommand property.
/// </summary>
private static void OnEnterKeyCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
 ICommand oldEnterKeyCommand = (ICommand)e.OldValue;
 ICommand newEnterKeyCommand = (ICommand)d.GetValue(EnterKeyCommandProperty);
 if (d is TextBox )
 {
   (d as TextBox).KeyUp += new KeyEventHandler(TextBoxBehaviours_KeyUp);
 }
}