Showing posts with label WPF. Show all posts
Showing posts with label WPF. Show all posts

Tuesday, 20 October 2015

Introduction

    In this post we will see how we can identify if the application has been maximized or it is restored to normal state. We will use the Resize event equivalent in WPF which is SizeChanged event. We will subscribe to this event and will check the window state to identify if the window has been maximized or it is restored to normal.
Application.Current.MainWindow.SizeChanged += WindowSizeChanged;
private void WindowSizeChanged(object sender, SizeChangedEventArgs e)
{
    this.HandleWindowState();
}
 
private void HandleWindowState()
{
    WindowState windowState = Application.Current.MainWindow.WindowState;
    if (windowState == WindowState.Maximized)
     {                    
     }
    else if (windowState == WindowState.Normal)
     {                    
     }            
}
And let’s not forget to clean it by unsubscribing to the SizeChanged event by
Application.Current.MainWindow.SizeChanged -= WindowSizeChanged;

Sunday, 7 June 2015


Introduction

WPF applications support rich media and graphics, this require styles and styles can be reusable across different window or element in WPF. Here we need a mechanism by which we can share this style across different window or say application. By adding the style in application resource file, we can share it across windows in application but not across application. Here reusable styles need to be utilized and in a managed way. Here WPF provide an easy way to manage these styles and other reusable resources which can be used across WPF windows and across application. This is called Resources Dictionary. We can define the styles in WPF XAML files and can manage all our useful styles for a particular application in a resource dictionary file. This resources dictionary can then be referred from other WPF projects and can use the styles in this resources dictionary in that project.

Using the code

Adding a resource dictionary is pretty simple. We have to select the project or folder in Solution Explorer and then right click and select “Add”. We will get a menu item called “Resource Dictionary”. Selecting that menu item will pop up the Add New Item wizard with the Resource Dictionary Item template selected. Rename the item as you wish. In a Resource Dictionary, we can keep our custom styles, Templates, custom definitions for Brush, Color, Background and a lot of other stuff. Most important thing is that we have to assign a key to each of them since it is a Dictionary and it stores the values besed on the key. Or perhaps, we can give names to the styles.

How to refer to Resource Dictionary and use it in WPF xaml.

In this section, we are going to see how we can import a resource file to a XAML file for a WPF Window, user control or a page.  We can refer to the resource dictionary that we created for our window resources section. Since we can have a resource dictionary for each control, we are going to merge the other resource files to the existing resource dictionary.

<Window […] >
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary 
                  Source="ResourceDictionaryReferencePath/ResourceDictionaryName.xaml">
                </ResourceDictionary>
                <ResourceDictionary 
                  Source=" ResourceDictionaryReferencePath/ResourceDictionaryName.xaml ">
                </ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    </Window>

How to refer to resource dictionary from another project.

If your resource dictionary is in a different project, then make sure that the project can be referred from the project that you need the resource. If not then WPF will throw an exception at runtime. Either add reference to that project or drop that project dll to your applications folder so that your application can refer to it. Here the source path depends on where you have added your dictionary. If you have added resource file to the root of your application, then you can refer to this file as

Source="ResourceDictionaryName.xaml"

If you have added this file to a directory in your project then you can refer to it as

Source= "ResourcesDirectoryReferencePath/MyResourceDictionary.xaml"

If you your resources dictionary is in another project then you can refer to it as

Source= "pack://application:,,,/ApplicationNameWhereResourceDictionaryResides; component/ResourceDictionaryName.xaml"


Introduction

 This post will help you in binding a command to a button, where the button is defined in a template say a data template. With normal command binding it won’t work. We need some sort of workaround to achieve this.

How to fix this.

 Here the requirement is to bind a command to an element which is defined in a template. When we do a normal command binding, it is not aware of the data context and will not resolve. We need to provide the binding with the data context. This can be achieved in many ways say you can do
<Button Content="{Binding}" Command="{Binding RelativeSource={RelativeSource Window}, Path=DataContext.ClickHandlerCommand }" />

<Button Content="{Binding}" Command="{Binding Path= ClickHandlerCommand, Source={StaticResource MainWindow}}" />

<Button Content="{Binding}" Command="{Binding Path= ClickHandlerCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

But these won’t work with all scenarios. But one solution will work with all scenarios. Define your data context as a static resource and refer it as the source of the binding. As shown below.

<Window […]
        xmlns:this="clr-namespace:Your.Namespace.For.The.ViewModel"
        […]>

    <Window.Resources>
        <this:MainWindowViewModel x:Key="Model" />

        <DataTemplate x:Key="ItemsDataTemplate">
          <Button Content="{Binding }" Command="{Binding Command, Source=                            {StaticResource Model}}" />
        </DataTemplate>

    </Window.Resources>

    <Window.DataContext>
        <this:MainWindowViewModel></this:MainWindowViewModel>
    </Window.DataContext>

        <Grid>
        <ItemsControl ItemTemplate="{DynamicResource ItemsDataTemplate"  ItemsSource="{Binding Collections, Mode=OneTime}" >
            
        </ItemsControl>
    </Grid>
</Window>

Monday, 19 January 2015

Introduction


In this post we will see how to add hot keys to WPF window. Hot keys are keyboard shortcuts with which we can easily navigate through the window without the help of a mouse. Hot keys are those which when pressing “Alt”+ hotkey character will take you to the control associated with that hot key.

Background


When we have a window, which have many controls we need hot keys which will help users to navigate through the UI controls. When users are used with keyboard, they tend to use keyboard itself and avoids mouse most of the time. Keeping such users in mind, we have to provide hot keys in our application window.

You can find the hot keys in an application by pressing the “Alt” button on your keyboard. When you press on the “Alt” button, all those hot keys will be shown as an underlined character. Now if you press “Alt” + “HotKey” you can navigate to that control. For example, if you take the Remote Desktop Connection window in your windows (type mstsc in your run window) and when you press “Alt” button, you can see an underline on each character which is associated with hotkeys. And now if you press “Alt” + that character you can navigate to the control associated with that hot key.
Here in this post we will see how to associate a hot key to WPF window.

Using The Code


Here we will create two textbox and two label associated with that text box. When we press “Alt” button, these labels will highlight the hot keys. When we press Alt + Hot key character, it will take the focus to those text box which is associated with that hot key. Let’s create two textbox and two label which is associated with the text box.
<Grid>

   <ItemsControl>
    <Label Content="FirstBox" Width="100" Height="28" Name="label1"/>
    <TextBox Name="textBox1" Text="Title" Height="50" ></TextBox>
   </ItemsControl>
   <ItemsControl>
    <Label Content="SecondBox" Width="100" Height="28" Name="label2"/>
    <TextBox Name="textBox2" Text="Title2" Height="50" ></TextBox>
   </ItemsControl>
</Grid>


Now let’s see how to associate hot keys to the labels. This is pretty much simple; just add an underscore before the character of the label content which you need as a hot key. Here we will make “F” as the hot key for our label1 and “B” as the hot hey for label2.
<Grid>
   <ItemsControl>
    <Label Content="_FirstBox" Width="100" Height="28" Name="label1"/>
    <TextBox Name="textBox1" Text="Title" Height="50" ></TextBox>
   </ItemsControl>
   <ItemsControl>
    <Label Content="Second_Box" Width="100" Height="28" Name="label2"/>
    <TextBox Name="textBox2" Text="Title2" Height="50" ></TextBox>
   </ItemsControl>
</Grid>


Remember our hot key is intended for textbox so we need some mechanism by which we can pass the control to the text box from labels. We can use the Target property of the Label control to assign the Label to the TextBox and this way we can set the access key for the TextBox. Now bind the label to the textbox using the target attribute.
<Grid>
   <ItemsControl>
    <Label Content="_FirstBox" Width="100" Height="28" Name="label1" Target="{Binding ElementName=textBox1}"/>
    <TextBox Name="textBox1" Text="Title" Height="50" ></TextBox>
   </ItemsControl>
   <ItemsControl>
    <Label Content="Second_Box" Width="100" Height="28" Name="label2" Target="{Binding ElementName=textBox2}"/>
    <TextBox Name="textBox2" Text="Title2" Height="50" ></TextBox>
   </ItemsControl>
</Grid>


Now run the code and see your hot keys working!

Wednesday, 10 December 2014

Introduction

In telerik WPF radgridview, when we apply grouping, we can find that some groups will automatically expand even if there is no user interaction. This mostly happens in scenario when there is some value change in rows which are grouped. This will also happen in other scenarios as well. This is a known bug in telerik radgridview at the time when this post is posted.
In this post you will find out how to block this bug with the help of a custom behavior. Here we will make use of mouse click event and GroupRowIsExpandedChanging events. Here subscribing to mouse click events may look tricky; in order to understand this, you have to refer to this post.

Introduction


In this post, we will find out how to find the group, if grouping is applied on the radgridview, in which the event occurred. Or how to find if the row clicked is group row or not.

If you have subscribed to the mouse click event properly, you will get call to the delegate which is registered to the click event. You can refer to this post for proper subscription of mouse click event.

Now if you are getting calls to the delegate, then it is easy to find the row in which the event occurred, you can refer to this post to find out how you can achieve this.

Now to find out how to find the group in which this event occurred, you have to do something like this as shown below.

How to achieve this?

private void GridViewRowMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
   var senderElm = e.OriginalSource as FrameworkElement;
   var currentRow = senderElm.ParentOfType<GridViewRow>();
   var parentGroup = senderElm.ParentOfType<GridViewGroupRow>();

   if (currentRow == null && parentGroup != null)
    {
       // clicked on grouped row.
    }

   if (currentRow != null)
    {
      // clicked on a row.
    }
}
Introduction

If you are able to subscribe to a mouse click event on a radgridView, then your immediate requirement could be to find the row in which the mouse click event occurred. In this post we will see how to achieve this. If you are not subscribing to mouse click event properly, then you can refer to this post.

Tuesday, 9 December 2014

Introduction

Subscribing to a row click event is not straight forward in WPF Telerik RadGridView. In this post we will see how we can achieve this.

Subscribing to a mouse click event would have been straight forward if all the rows were available at the time of gridview loaded event. But as in most scenarios, not all rows are available at this time, so when you subscribe to a normal Mouse Click event, only a click on the Header row will trigger the events. As the GridView can be updated with values at a later stage, it is not easy to subscribe to those rows which are loaded at a later stage.

Monday, 1 September 2014

This could be one of the required features if you are working on WPF. But this won’t work without some additional work. Here in this post we will see how we can drag and drop items from RadTreeView to RadGridView. This is achieved with the help of behaviors.

Tuesday, 26 August 2014

Introduction

Worried over this exception? This happens when you haven’t set the Path= on binding. By default WPF binding will take the Path= part by default. But on controls which have a two way binding by default, this seems to be not working. You may have to set it explicitly.

Thursday, 21 August 2014

TextWrapping is required when your text to display has to align itself inside a control. TextWrapping should work seamlessly when your control is of fixed height and width. But this won’t be the scenario in all cases. When we have a dynamic parent control whose width and height cannot be predicted, we would like the TextBlock which is placed inside it to adjust itself to fit into the container. In this case we would prefer to have TextBlock decide on the height and width based on the parent control. So we won’t set any width or height.

Thursday, 10 July 2014


It is often a requirement when we use RadSplitContainer and we want to set width or height to RadSplitContainer. Here in this post we will see how to achieve this. When we use RadSplitContainer, we would like it to occupy a small space initially and if required we can drag it to take more space. This is normally achieved by setting the width for the control. If we are using two RadSplitContainer and if we wish to set these RadSplitContainer widths in 1:3 ratios, we may not be able to achieve this easily if you are not an expert in it. So here is a post to relieve your effort to achieve this.

Thursday, 26 June 2014

 RadPane in telerik controls can show a header. We normally use the Header property to set the header for RadPane. This works most of the time. But in some scenarios, say for example when we use nested RadPane, this kind of usage doesn't seem to work. The header suddenly disappears. This is a know issue in telerik.

Friday, 9 May 2014

Issue:

At times we will face with a situation where we need to show an image from another project in the same solution. Say for example: If you are building an enterprise application then we will modularize the application. And at times we want to show some image from this module in the main shell view. This at times can run you crazy. Here we will see how to show an image from a different module in the shell view.

Wednesday, 16 April 2014


Issue:

Often we face a situation where we have defined a DataTemplate and we need to bind to a property, most often to a Command in ViewModel. To achieve this we will define the binding and will set a RelativeSource for that binding which in some cases can ends up in an error like this. BindingExpression path error: … property not found on 'object' … BindingExpression:Path=… DataItem=…

Sunday, 13 April 2014

Issue:

When I was developing some XAML page, I encountered one situation where I experienced some intermittent bug from WPF. Some of my buttons will go disabled at times even if the CommandParameter bind to a buttons command has proper value to enable button. Below is the solution for this.
Issue: 

You all may have experienced an annoying behavior of visual studio while developing WPF XAML.
Say for example Visual Studio consumes large amounts of memory and shows Not Responding message on a regular basis while designing XAML
This is because of the XAML designer (Microsoft Visual Studio XAML UI Designer) which visual studio loads while editing XAML. There will be one for each XAML that you open for editing.
Issue:

You can achieve this with the help of Behavior in WPF. Create one multiselect behavior and attach it to RadGridView. This way you can avoid any code behind code altogether and can implement multiselect in proper MVVM way.
Issue: 

How to Sort RadGridView in ascending order based on a column value when it is loaded.
Introduction:

In this article you will see how to implement multiselect in WPF DataGrid in proper way when you are following MVVM pattern. In this article you will see how to implement a behavior to your DataGrid so that we can achieve multiselect.
Behaviors are introduced with Expression Blend, to encapsulate pieces of functionality into a reusable component. These components can then be attached to controls to give them an additional behavior.