WPF



If you are creating Windows Services you may run into this error:

Error 1001. The specified service has been marked for deletion

At first I used to restart my machine to get rid of it, but there is a (much) simpler way: close the Services Manager and you will never encounter this error!

Marzio.


Hi,
when you are developing your applications using VS 2010 and unfortunately your TFS server became unreachable, your Visual Studio 2010 stuck!
Since you are unable to tell to VS that your TFS is unreachable you should waiting for VS until it detects that is unable to connect to TFS… This is really annoying and this makes you wasting your precious time…

Bernhard Tschirren has developed a VS addon for adding the Go Off Line button into VS Source Control Menu! Using this button befor opening your your .sln you can avoid the VS stuck even if your TFS is offline 🙂

Here you are the GoOffline VS Ads link (for installing just double click it after downloading): Click Here

Happy coding and stay tuned!
Marzio.


Hi,
WPF provides two main ways for implementing data validation: ValidationRule and IDataErrorInfo. In this post is focused on IDataErrorInfo.

The demo project is available here and the below images displays the result from an UI point of view:

Using ValidationRule you are able to validate user inputs directly into UI (View). This way consists in implementing a class that extends .Net ValidationRule and using your class into Binding. You can check an example here.

Using IDataErrorInfo you are able to validate user inputs in both UI and Business Logic too (ViewModel). This way is more MVVM oriented and allow performing validation in different layers (View and ViewModel) sharing a common validation code.

The first step consists into implementing IDataErrorInfo interface into the class that contains a Property that will be involved in UI binding. IDataErrorInfo consists into two properties: the Error property that tells what is wrong with this object, and the Item property that gets the error message of the specified property. Regardless of your object you can implement IDataErrorInfo interface in the following way:

        #region IDataErrorInfo Members

        string IDataErrorInfo.Error { get { return null; } }

        string IDataErrorInfo.this[string propertyName]
        {
            get { return this.GetValidationError(propertyName); }
        }

        #endregion // IDataErrorInfo Members

You might ask “why”? The answer is easier you can imagine: the GetValidationError method we are going to implement will be also used by IsValid property into other layers (typically ViewModel).
In other words the IDataErrorInfo is used by .Net into binding expressions, while IsValid property can be used into code behind layers.

Here below the rest of the code:

        public bool IsValid
        {
            get
            {
                foreach (string property in ValidatedProperties)
                    if (GetValidationError(property) != null)
                        return false;

                return true;
            }
        }

        static readonly string[] ValidatedProperties = 
        { 
            "ServerIPAddress"
        };

        private string GetValidationError(string propertyName)
        {
            string error = null;

            switch (propertyName)
            {

                case "ServerIPAddress":
                    error = ValidateIPAddress();
                    break;

            }

            return error;
        }

        private string ValidateIPAddress()
        {

            if (String.IsNullOrEmpty(ServerIPAddress))
            {
                return "Please enter an IP Address.";
            }

            if (ServerIPAddress.Contains(" "))
            {
                return "Blank characters are not allowed in IP Address.";
            }

            string[] parts = ServerIPAddress.Split('.');
            if (parts.Length != 4)
            {
                return "IP Address should be four octets, seperated by decimals.";
            }

            foreach (string p in parts)
            {
                int intPart;

                if (!int.TryParse(p, out intPart))
                {
                    return "Each octet of an IP Address should be a number.";
                }

                if (intPart < 0 || intPart > 255)
                {
                    return "Each octet of an IP Address should be between 0 and 255.";
                }
            }

            return null;
        }

Finally the following XAML Code is used for validating data into the View:

        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel LastChildFill="True">
                            <TextBlock Text="*" 
                                       Foreground="Red"  
                                       DockPanel.Dock="Right" 
                                       Width="16" Height="16" 
                                       Margin="4,0,0,0" />
                            <Border BorderBrush="Red" BorderThickness="1">
                                <AdornedElementPlaceholder />
                            </Border>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip" 
                            Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
...
        <TextBox MaxLength="15"
                    Width="150" 
                    Text="{Binding Path=MyDummyItem.ServerIPAddress, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />

Stay tuned and happy coding!


Hi,
today I want to share with you the fast way for creating a dropdown menu on WPF.
You can download sample code here.

The following image display the result (remark that you can customize the Button look&feel as you need):

The idea is to use the WPF ContextMenu modifying the way to open it.
The first step consist in creating a Button with a ContextMenu and disabling the ContextMenuService for this Button object. In this way the right click does not show the ContextMenu. Here the code:

        <Button Content="Click Me" 
                Click="Button_Click"
                ContextMenuService.IsEnabled="False" 
                Margin="42,40,89,72">
            <Button.ContextMenu>
                <ContextMenu >
                    <MenuItem Header="Menu 1"/>
                    <MenuItem Header="Menu 1"/>
                    <MenuItem Header="Menu 1"/>
                    <MenuItem Header="Menu 1"/>
                </ContextMenu>
            </Button.ContextMenu>
        </Button>

The second step consist in displaying the ContextMenu when the button is clicked. This is achieved by few lines of code:

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            (sender as Button).ContextMenu.IsEnabled = true;
            (sender as Button).ContextMenu.PlacementTarget = (sender as Button);
            (sender as Button).ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
            (sender as Button).ContextMenu.IsOpen = true;
        } 

Stay tuned and happy coding 😉
Marzio.


Hi,
in this posts I am going to present a nice control I developed for asynchronously loading image using WPF.
This control is implemented into the PhotoLoader DLL and all the available functionalities are tested into a test client that is included into the solution. You can download PhotoLoder and Test client here.

Problem
If you try to load a lot of big images directly via Image’s Source property you will notice that your application will stuck. Performances became better when you load images via BitmapFrame and using the Thumbnail property, however not all images have embedded Thumbnail and, even if your images have it, your application will not responsive during loading.

Solution
I developed an additional attached property to be used with WPF Image and that allows Images to be loaded asynchronously by a background Thread. I put this property and others into the PhotoLoader DLL that can be used for free into your applications 🙂

The attached property performing asynchronous loading is the Loader.Source and it must be used in replace of Image.Source property.

PhotoLoader DLL provides also others Attached Properties that allows developers displaying and customizing the ‘waiting animation’ as well as managing errors.

Example of usage

                    <Image PhotoLoader:Loader.DisplayOption="FullResolution"
                           PhotoLoader:Loader.Source="{Binding Path=FirstFileInCollection}"
                           PhotoLoader:Loader.DisplayWaitingAnimationDuringLoading="{Binding Path=DisplayAnimationDuringLoading}"
                           PhotoLoader:Loader.DisplayErrorThumbnailOnError="{Binding Path=DisplayErrorImageOnError}">
                    </Image>

Screeshots
The following screenshots give you an idea about PhotoLoader Attached Properties functionalities.

Documentation – Loader Attached Properties
PhotoLoader exposes the following Attached Properties via the static Loader class:

  • Source: string representing the path of the image to display. Right now it is possible to specify only file names of images stored into a disk. Once set, the PhotoLoader automatically performs the asynchronous loading displaying a nice loading animation.
  • SourceType: it is an enum indicating the way used to specify the Source. Right now the only source type allowed is LocalDisk.
  • DisplayOption: it is an enum indicating the image resolution to be used for displaying the image. Supported resolutions: Preview and FullResolution. Notice that using FullResolution requires more memory than Preview modality. Avoid to display a large number of huge images using FullResolution for all, othxerwise an OutOfMemoryException can happen. Normally in an application only few images at time are displayed in full resolution and does not make sens displaying thumbnails using full resolution.
  • DisplayWaitingAnimationDuringLoading: boolean value used for displaying (or not) the default waiting animation during loading.
  • DisplayErrorThumbnailOnError: boolean value used for displaying (or not) a default thumbnail error in case the image cannot be loaded (wrong path, unknown image format…)
  • IsLoading: boolean value set by PhotoLoader indicating if the loading of the specified image is in progress or it is finished. It can be used for customizing loading animation.
  • ErrorDetected: boolean value set by PhotoLoader indicating if an error happened during loading. It can be used for managing the failed loading.

Hi,
in these days I needed to override the default highlight color used for marking selected items in GridView of WPF Application running on Windows 7.
First of all I noticed that the well known strategy that consist in overriding the SystemColors.HighlightBrushKey didn’t work for ListView that contains GridView on Windows 7 even if the same strategy works fine in ListBox and ListView (that does not have GridView inside) on both Windows XP and 7. This strange behavior is also described in the following msdn post: http://social.msdn.microsoft.com/Forums/en/wpf/thread/1f62b66f-bdcb-4092-8568-a8fa4d39ea9b.

In order to solve that problem, my idea was to define a global style for ListViewItem, but ListViewItem Style  must be different for ListView that contains GridView and ListView without GridView.
In fact when a ListView contains a GridView, the ListViewItem Style must display items via GridViewRowPresenter.
Instead when ListView does not contains the GridView, the ListViewItem Style must display item via ContentPresenter.
This implies to implement a Trigger into ListViewItem Style in order to hide\show the GridViewRowPresenter or the ContentPresenter.

Below a screenshot of ListView and ListView + GridView using a common ListViewItem Style! The solution is downloadable here.

Highlighted item in ListView via ListViewItem Style

And here you are the final working solution for defining a common ListViewItem Style. Notice the Triggers in lines 36-38 that shows/hides the ContentPresenter.

        <Style TargetType="{x:Type ListViewItem}" x:Key="{x:Type ListViewItem}" >
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="Foreground" Value="Black"/>
            <Setter Property="UIElement.SnapsToDevicePixels" Value="True"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListViewItem}">

                        <Border SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" 
                            BorderThickness="{TemplateBinding BorderThickness}" 
                            BorderBrush="{TemplateBinding BorderBrush}"
                            Background="{TemplateBinding Background}">

                            <Grid>

                                <!-- This is used when GridView is put inside the ListView -->
                                <GridViewRowPresenter Content="{TemplateBinding ContentControl.Content}"
                                                  HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}" 
                                                  VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}" 
                                                  SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"/>

                                <!-- This is used for ListView that does not use GridView -->
                                <ContentPresenter x:Name="contentPresenter"
                                              Content="{TemplateBinding ContentControl.Content}" 
                                              Visibility="Collapsed"
                                              ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}" 
                                              ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}" 
                                              HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}" 
                                              VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}" 
                                              SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"/>
                            </Grid>

                        </Border>

                        <ControlTemplate.Triggers>
                            <Trigger Property="GridView.ColumnCollection" Value="{x:Null}">
                                <Setter TargetName="contentPresenter" Property="Visibility" Value="Visible"/>
                            </Trigger>

                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="Background" Value="#FFB3D0E5" />
                            </Trigger>

                            <Trigger Property="IsEnabled" Value="False">
                                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
                            </Trigger>
                        </ControlTemplate.Triggers>

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

Stay tuned!
Marzio.


Hi guys,
today I wanna share with you a MultiSelectionTreeView control that I coded by myself a couple of day ago.
The source code can be downloaded here.
Feel free to reply at this post with any question or comments you have.

The controller provide the following functionalities:

  • three different selection modalities can be specified setting SelectionMode property. Supported Selection Modalities are: 
    • SingleSelectionOnly: same behaviors of  classic WPF TreeView,
    • MultipleSelectionOnly: every click select/unselect the clicked item, 
    • KeyboardModifiersMode: multiple select  items when CTRL key is pressed
  • retrieving selected nodes using SelectedItems property
  • data binding support, including HierarchicalDataTemplate
  • tree navigation using arrows keyboards up, down and left, right for expanding and collapsing nodes
  • helpful TreeItem nodes methods like:
    • SelectAllExpandedChildren/UnselectAllChildren,
    • GetDepth,
    • GetNextNodeAtSameLevel, GetPreviousNodeAtSameLevel
  • look and feel can be overridden

The default look and feel is shown in the picture below:

Happy Coding,
Marzio.

Next Page »