Showing posts with label XAML. Show all posts
Showing posts with label XAML. Show all posts

Dock panel like animated buttons in WPF(XAML)

Like dockpanel buttons(Buttons which grows up as mouse enters on button) in windows, we can have the buttons in WPF without writing any C# or VB code. This can be achieved by using EventTriggers & DoubleAnimations.


As mentioned in above image as mouse enters on Recycle Bin icon, it grows up, similar thing can be achieved in wpf, sample XAML is written below.

Code:

TargetInvocationException was unhandled "Exception has been thrown by the target of an invocation." issue in WPF

In WPF, most probably the issue occurs when we are accessing null object in the constructor of the code file of the XAML or If you are invoking "PropertyChanged" event without having null check inside the constructor.



Example 1:

How to declare Hashtable or ArrayList in XAML.

To declare Hashtable or ArrayList in xaml, we need to include the System.Collection namespaces in XAML by using the below key
        xmlns:col='clr-namespace:System.Collections;assembly=mscorlib'
After declaring the namespace we can use all the class of System.Collection namespace with col: prefix

Code to Declare the HashTable in XAML:

<col:Hashtable x:Key='hash'>
       <col:DictionaryEntry x:Key='hashEntry1' Key='1' Value='a'></col:DictionaryEntry>
       <col:DictionaryEntry x:Key='hashEntry2' Key='2' Value='b'></col:DictionaryEntry>
       <col:DictionaryEntry x:Key='hashEntry3' Key='3' Value='c'></col:DictionaryEntry>
       <col:DictionaryEntry x:Key='hashEntry4' Key='4' Value='d'></col:DictionaryEntry>
</col:Hashtable>

Code to Declare the ArrayList in XAML:

Change Style of ListBoxItem when we use ItemTemplate in ListBox.

We will see how can we change background and foreground of any ListBoxItem on MouseOver or on Selection, and for ListBoxItem, ItemTemplate is being used.

Consider a ListBox in XAML, in which, ListBoxItem contains multiple Label via ItemTemplate. Now you want the background color and the text color of the Labels to be changed on Mouse Over or on Selection of the Item. To achieve this we can use following style:

Scenario to Achieve:



To change the Foreground of the text we will use following style on the Labels:

<Style TargetType="{x:Type Label}" x:Key="listBoxLabel">
  <Setter Property="Foreground" Value="Black"></Setter>
    <Style.Triggers>
      <!--Triggers for the IsSelected Property to check selection status-->
      <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsSelected}" Value="True">
            <Setter Property="Foreground" Value="White"></Setter>
      </DataTrigger>
      <!--Triggers for the IsMouseOver Property to check focus status-->
      <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsMouseOver}" Value="True">
          <Setter Property="Foreground" Value="Red"></Setter>
      </DataTrigger>
    </Style.Triggers>
 </Style>

To change the Background of the Item we will write following style for the ListBox:

WPF StringFormat example in Binding



In this small article we will see how we can use StringFormat when we use Binding.
In the example we have use one Date Picker and one TextBlock. The TextBlock isbound with the SelectedDate property of the DatePicker.And we have used StringFormat property to modify the text shown in TextBlock.

Sample Code:

WPF How to use Resource Dictionary in C#



To know what is Resource Dictionary,example of Resource dictionary, how we can add Resource Dictionary and how we can use it from XAML visit here:

Now there may be a case where we need to access a resource dictionary that we have defined in our project, from C# code.
If we have already merged our resource dictionary in XAML, it is easy to access the inner resources using thecontrol.FindResource("<<ResourceKey>>"); method.
 But, if we haven’t merged the resources in XAML and we still need to use the resource dictionary, we have options to use it directly inC# code. 
We have modified the example given here WPF How to use Resource Dictionary in XAML. where we were using ResourceDictionary from XAML.
Below is the XAML and code snippet:
XAML Code:
<UserControl x:Class="WPF_Sample_Project_Test.ResourceDictionaryExample"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
        <Grid>
        <Button x:Name="btnRound"  />
    </Grid> 
</UserControl>
C# Code:

WPF How to use Resource Dictionary in XAML



In this article, we will learn how we can use merge a resource dictionary in WPF XAML.


As we all know, that WPF applications supports rich media and graphics support, styles and templates should be managed in such a way that they can be reused. Styles can be defined in the same XAML file or all the styles and templates which are reusable across different screens can be accumulated in a Resource Dictionary File. 


What is Resource Dictionary?


In Resource Dictionary, one can write reusable styles, DataTemplates, ControlTemplates. One can also define custom definitions for Brush, Color, Background etc.

Each of these custom defined style or template is called as resource and a unique key must be given to each resource.


Steps to add Resource Dictionary

Create Watermark / HintText Textbox in WPF / XAML

In this example we shall see, how we can add watermark / hint text to wpf controls like textbox. In modern UI based application it is being used very extensively. A snapshot of its usage is added below.












As we can see it eliminates the need of labels against each input controls.
To achieve the same behavior in WPF, we will use System.Windows.Media.VisualBrush. In this visual brush we will add textblock,  and make stylish as we want for the application.

WPF: How to change the style of selected and Focused Row with AlternateRowColor of DevExpress Grid Control

To change the style of the selected row we will write a Trigger and will apply style for the row in the trigger. For that we will check for the SelectionState for selected Row & IsFocusedRow for the Focused Row Property.

Trigger For Focused Row

<Trigger Property='dxg:DataViewBase.IsFocusedRow' Value='True'>
       <Setter Property='Background' Value='{DynamicResource FocusedRowBackgroundStyle}'/>
       <Setter Property='BorderBrush' Value='#F2F2F2'/>
       <Setter Property='Foreground' Value='Black'/>
       <Setter Property='BorderThickness' Value='2'/>
 </Trigger>

Trigger For Selected Row


<DataTrigger Binding="{Binding Path=SelectionState}" Value="Selected">
    <Setter Property='Background' Value='{DynamicResource SeletedRowBackgroundStyle}'/>
    <Setter Property='BorderBrush' Value='#F2F2F2'/>
    <Setter Property='Foreground' Value='Black'/>
    <Setter Property='BorderThickness' Value='2'/>
</DataTrigger>

Sample XAML Code

WPF: AlternateRowColor style in devexpress GridControl

Here I am demonstrating how can we assign alternate Row color to a devexpress grid control. To do so we will have to use MultiDataTrigger. In the MultiDataTrigger, we will check that if the row is even and not selected then Even row color will be assigned, if the row is odd and not selected than odd row color will be applied. similarly if the row is selected than no color will be applied and default selection state will be applied.

XAML Code

Set parent control's property with change in child control's property value in XAML (Using AncestorType binding)

In XAML, one can set parent's property from the change in a property of child control. To do so we can use AncestorType binding for the child control.

Consider an example we have a StackPanel having a TextBox. Which ever color user enters in the textbox must be reflected in the StackPanel's Background.

XAML

<StackPanel Orientation="Vertical" x:Name="stk">             <StackPanel Orientation="Horizontal">                 <TextBlock Text="Enter Color:"></TextBlock>   <TextBox x:Name="colorName" Width="150" BorderBrush="Brown"      Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,         AncestorType={x:Type StackPanel}}, Path=Background,Mode=OneWayToSource}">   </TextBox><TextBox Text="Color Format = ARGB"></TextBox>             </StackPanel> </StackPanel>

Output

WPF: Working with Event Triggers

While an ordinary trigger waits for a property change to occur, an event trigger waits for a specific event to be fired. You might assume that at this point you use setters to change the element, but that’s not the case. Instead, an event trigger requires that you supply a series of actions that modify the control. These actions are used to apply an animation.

Here I am taking a very simple example to explain  how can we use event triggers, Suppose I have a button and a textblock on my window. I want the controls to be grown up when mouse enters and reset as mouse leaves


WPF: Rotation and Scale Transform Example



This is a simple example which explains how we can apply render and scale transform.
In this example we have an image and we will apply scale and render transform to this image.
Render transform will help us to rotate the image at specific angle. Similarly, Scale Transform will reduce or increase the size of image in X or Y axis direction.

In the example we have used: 
1)      Image 
2)      3 Scrollbars which are bounded with angle of rotation, scale x and scale y property.

Here is the XAML source code for the same:


Set selected row index in DevExpress Grid Control by C# code

In DevExpress grid control there is no direct property to set selected row index from C# code if you need to do so. To achieve this functionality one needs to define TableView for the DevExpress grid control. The TableView is defined under <dxg:GridControl.View></dxg:GridControl.View> tag.

To add DevExpress Grid you will require
xmlns:dxg='http://schemas.devexpress.com/winfx/2008/xaml/grid'

In the TableView there is a property called "FocusedRowHandle" which is used to set the selected row index in the GridControl

Consider Sample XAML Written Below
<StackPanel>
   <dxg:GridControl Height='300' Grid.Column='0' Grid.Row='1' x:Name='grdDetail' IsFilterEnabled='False' IsManipulationEnabled='False'> <dxg:GridControl.Columns> <dxg:GridColumn Header='SeqNo' AllowResizing='False' Width='30'  FieldName='[SeqNo]' HorizontalHeaderContentAlignment='Center' AllowSorting='False'>               <dxg:GridColumn.CellTemplate>                   <DataTemplate>                     <TextBlock HorizontalAlignment='Left' VerticalAlignment='Center'  Text='{Binding Path=RowData.Row.[SeqNo]}'></TextBlock>                   </DataTemplate>               </dxg:GridColumn.CellTemplate>                             </dxg:GridColumn>          <dxg:GridColumn Header='RollNo' FieldName='[RollNo]' AllowSorting='False'>               <dxg:GridColumn.CellTemplate>                   <DataTemplate>                    <TextBlock HorizontalAlignment='Right' VerticalAlignment='Center'  Text='{Binding Path=RowData.Row.[RollNo]}'></TextBlock>                   </DataTemplate>              </dxg:GridColumn.CellTemplate>          </dxg:GridColumn>          <dxg:GridColumn Header='Name' FieldName='[Name]' AllowSorting='False'>               <dxg:GridColumn.CellTemplate>                   <DataTemplate>                    <TextBlock HorizontalAlignment='Center' VerticalAlignment='Center' Text='{Binding Path=RowData.Row.[Name]}'></TextBlock>                   </DataTemplate>               </dxg:GridColumn.CellTemplate>          </dxg:GridColumn>          <dxg:GridColumn Header='Marks' FieldName='[Marks]' Width='50'  HorizontalHeaderContentAlignment='Center' AllowSorting='False'>                <dxg:GridColumn.CellTemplate>                  <DataTemplate>                    <TextBlock HorizontalAlignment='Right' VerticalAlignment='Center'  Text='{Binding Path=RowData.Row.[Marks]}'></TextBlock>                   </DataTemplate>                </dxg:GridColumn.CellTemplate>          </dxg:GridColumn>          <dxg:GridColumn Header='Rank' FieldName='[Rank]' Width='50'  HorizontalHeaderContentAlignment='Center' AllowSorting='False'>               <dxg:GridColumn.CellTemplate>                 <DataTemplate>                 <TextBlock HorizontalAlignment='Right' VerticalAlignment='Center'  Text='{Binding Path=RowData.Row.[Rank]}'></TextBlock>                   </DataTemplate>                </dxg:GridColumn.CellTemplate>          </dxg:GridColumn>        </dxg:GridControl.Columns>        <dxg:GridControl.View>        <dxg:TableView Name='tblViewDetail' AllowColumnFiltering='False'  AllowEditing='False' AllowGrouping='True' AllowResizing='True'  AllowSorting='True' AutoWidth='True' ShowGroupPanel='False'  ShowIndicator='False' ShowVerticalLines='False'>         </dxg:TableView>        </dxg:GridControl.View>    </dxg:GridControl>    <StackPanel Orientation="Horizontal">        <Button Content="Select 1st Row" Click="Button_Click" x:Name="Sel1"></Button>        <Button Content="Select 2nd Row" x:Name="Sel2" Click="Sel2_Click"></Button>        <Button Content="Select 3rd Row"  x:Name="Sel3" Click="Sel3_Click"></Button>   </StackPanel> </StackPanel>

Now In this XAML we will add ItemSources by C# Code as well as selected row will be set by c# code. The C# Code will be as followed