Showing posts with label WPF. Show all posts
Showing posts with label WPF. 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:

ComboBox in WPF DataGrid's Column Header

Here, In this article, we are going to discuss, how can we add framework elements in WPF Datagrid's column header. We will add combo box in  the header. To add Combobox in the Header of DataGrid we use [GridColumn].Header tag. In the tag we can add any element directly.

<tools:DataGridTextColumn.Header>
     <ComboBox x:Name='txtCbo75P' ItemsSource='{StaticResource StringArrayResource}' SelectedIndex='0'></ComboBox>
</tools:DataGridTextColumn.Header>

Now suppose we have to create Grid as below:

In this case for the forth column rather than giving header text directly, we shall use above code

XAML

Create Nested headers in WPF DataGrid

In WPF many times we may require to render a data grid which contains multilevel headers, for example we  have columns FirstName, LastName, Address1, Address2, City, State. Now we have to render a grid in which we have these columns these columns will have group name above the column header. It means there will be another level of header above these. In our case FirstName and LastName will be under Name, and Address1, Address2, City and State Columns will be under the Address.

Sample snapshot is displayed below.


XAML:

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

WPF Disable ListBox Selection Workaround

In this example, we will demonstrate how we can disable the WPF listbox selection.
As we all know, that there is no property in ListBox such as "SelectionMode"= None.
So, instead of disabling the listbox selection, we can override the system colors in such a way that , even when the list box is selected, it appears as if the listbox is not selected.
We are overriding the "HighlightBrushKey" and "ControlBrushKey" as Transparent and "HighlightTextBrushKey" as Black. So the background which gets selected will remain transparent and the foreground will turn black.
Here is the source code for the same:

<Grid >
        <Grid.Resources>
             <x:Array x:Key="StringArrayResource" Type="sys:String">
                <sys:String>List Value1</sys:String>
                <sys:String>List Value2</sys:String>
                <sys:String>List Value3</sys:String>
            </x:Array>
        </Grid.Resources>

  <ListBox Grid.Row="0" ItemsSource="{DynamicResource StringArrayResource}">
            <ListBox.Resources>
                    <SolidColorBrush x:Key='{x:Static SystemColors.HighlightBrushKey}' Color='Transparent'/>
                    <SolidColorBrush x:Key='{x:Static SystemColors.HighlightTextBrushKey}' Color='Black'/>
                    <SolidColorBrush x:Key='{x:Static SystemColors.ControlBrushKey}' Color='Transparent'/>
                </ListBox.Resources>        
        </ListBox>
</Grid>

Screenshots:
Before Overriding System Colors:
 After Overriding System Colors:



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