Right place to discuss about Silverlight and WPF. Lets join with me to share more information about this amazing technology.
Saturday, June 30, 2007
How to Bind an Adorner to an Element?
Call the static method GetAdornerLayer to get an AdornerLayer object for the UIElement to be adorned. GetAdornerLayer walks up the visual tree, starting at the specified UIElement, and returns the first adorner layer it finds. (If no adorner layers are found, the method returns null.)
Call the Add method to bind the adorner to the target UIElement.
The following example binds a SimpleCircleAdorner (shown above) to a TextBox named myTextBox.
C#
myAdornerLayer = AdornerLayer.GetAdornerLayer(myTextBox);
myAdornerLayer.Add(new SimpleCircleAdorner(myTextBox));
Have a fun with WPF programming. Enjoy......!
Note:
Using Extensible Application Markup Language (XAML) to bind an adorner to another element is currently not supported.
Monday, June 25, 2007
What is this "Content Model" in WPF?.
In contrast WPF doesn't make nearly as many assumptions about the types of content you would like to display inside a given control. Content of different kinds can be nested freely inside other elements. The following XAML snippet defines a button. Inside the button is contained some text, an ellipse, a text box and a combo box. Inside the combo box is more text and another ellipse.
XAML :
Although this example is not the type of functionality that has been required for in any application that I have ever written, it is this flexible way that content can be nested and composed that underpins many of the powerful things that can be done in WPF.
Have fun with WPF programming... Enjoy..
Friday, May 4, 2007
Resources In WPF
Format of Resources:
<SomeType x:Key=”keyname” ...> </SomeType>
Type of Resources :
- Static Resources
- Dynamic Resources
Static Resources
XAML elements can reference the resources using the key using markup extension. The particular markup extension you use with resources is named StaticResource.
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib">
<StackPanel.Resources>
<s:Double x:Key="fontsizeLarge">18.7 </s:Double>
<s:Double x:Key="fontsizeSmall"> 14.7 </s:Double>
</StackPanel.Resources>
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Margin="24">
<Button.FontSize>
<StaticResource ResourceKey="fontsizeLarge" />
</Button.FontSize>
Button with large FontSize
</Button>
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Margin="24" FontSize="{StaticResource fontsizeSmall}" >
Button with small FontSize </Button>
</StackPanel>
Here fontsizeSmall and fontsizeLarge is the static resources. And we have created that resources in element stackpanel. So we can use that resources only child of stackpanel. In case if we declared that resources in window section means we can use anywhere in the single source code. That means insidea of window element.method of accessing static resources .
<Button.FontSize> <StaticResource ResourceKey=”fontsizeLarge”>
</Button.FontSize>
(or)
FontSize=”{StaticResource fontsizeLarge}”
Note:
Forward reference is not allowed in resource reference.We can define control or element as a resource. But we cant use twice. because it will create only one instance.
Creating resources using C# code.
elementname.Resource.Add(“resource name”,value);
Finding Resources
Application.Current.FindResource(key);
Application Resources
we can define resources in the Application file . And we can access those resources from anywhere in the application. For that we need create resources under MyApp.xaml file which is created by the VisulaStudio.
<Application.Resources>
</Application.Resources>
XAML defines a markup extension named x:Static specifically to reference static properties of fields.It also works with enumeration members.
Example :
some static property from a class named MyClass.
<Button.Content>
<x:Static Member=”MyClass:PropertyName” />
</Button.Content>
Dynamic Resource
With StaticResource the key is used to access the object once and the object is retained . When we use the DynamicResource the key is retained and the object is accessed when its needed. The primary purpose of DynamicResource is to access system resources such as colors.
Resources:
if we want share multiple resources among multiple applications. We can use resource dictionary.
Example: SampleResource1.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<LinearGradientBrush x:Key="brushLinear">
<LinearGradientBrush.GradientStops>
<GradientStop Color="Pink" Offset="0" />
<GradientStop Color="Aqua" Offset="1" />
</LinearGradientBrush.GradientStops> </LinearGradientBrush>
</ResourceDictionary>
SampleResource2.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<RadialGradientBrush x:Key="brushRadial"> <RadialGradientBrush.GradientStops>
<GradientStop Color="Pink" Offset="0" />
<GradientStop Color="Aqua" Offset="1" />
</RadialGradientBrush.GradientStops>
</RadialGradientBrush>
</ResourceDictionary>
MyApp.xaml(Application file)
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" StartupUri="UseCommonResourcesWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MyResources1.xaml" />
<ResourceDictionary Source="MyResources2.xaml" /> </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
we can access the resources like this .
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Title="Use Common Resources" Background="{StaticResource brushLinear}">
<Button FontSize="96pt" HorizontalAlignment="Center" VerticalAlignment="Center" Background="{StaticResource brushRadial}">
Button
</Button>
</Window>
Enjoy!!!!!!!!!! If you have a question or you cant get anything in this feel free to comment. I will try to give you as soon as possible.
Tuesday, May 1, 2007
XML DataBinding In WPF
XML DataBinding concept is used to retrieve the data from XML file using XmlDataProvider in XAML language. Windows Presentation Foundation makes it possible to create user interfaces that use data binding wholly in an XML-based markup. When working with XAML we can use the XmlDataProvider object to retrieve XML data and provide it to controls.
Format for Accessing XMLData
XMLDataProvider :
With an XmlDataProvider, the underlying data that can be accessed through data binding in your application can be any tree of XML nodes. In other words, an XmlDataProvider provides a convenient way to use any tree of XML nodes as a binding source. First, we create a XmlDataProvider that will retrieve data asynchronously from the given address and create the data collection with XPath.
XPath :
The XPath properties in WPF are handled by the XmlNode. SelectNodes method. You can modify the XPath queries to get different results. Here are some examples for the XPath query.
- XPath="Book[1]" - will return the first book element ("XML in Action"). Note that XPath indexes are based on 1, not 0.
- XPath="Book[@*]" - will return all book elements with any attributes.
- XPath="Book[last()-1]" - will return the second to last book element ("Introducing Microsoft .NET").
- XPath="*[position()>3]" - will return all of the book elements except for the first 3.
Source :
We can specify the xml file source address in source attribute.
Example 1:
This sample will help you to get data from external XML file named as BookData.xml and binded with listbox.
BookData.xml
<Book ISBN="0-7356-0562-9" Stock="in">
<Title>XML in Action</Title>
<Summary>XML Web Technology</Summary>
</Book>
<Book ISBN="0-7356-1370-2" Stock="in">
<Title>Programming Microsoft Windows With C#</Title>
<Summary>C# Programming using the .NET Framework</Summary>
</Book>
<Book ISBN="0-7356-1288-9" Stock="out">
<Title>Inside C#</Title>
<Summary>C# Language Programming</Summary>
</Book>
<Book ISBN="0-7356-1377-X" Stock="in">
<Title>Introducing Microsoft .NET</Title>
<Summary>Overview of .NET Technology</Summary>
</Book>
<Book ISBN="0-7356-1448-2" Stock="out">
<Title>Microsoft C# Language Specifications</Title>
<Summary>The C# language definition</Summary>
</Book>
</Books>
Window1.xaml
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="410" Height="350" Background="White">
<StackPanel.Resources>
<XmlDataProvider x:Key="BookData" Source="bookdata.xml" XPath="Books"/>
<DataTemplate x:Key="BookDataTemplate">
<TextBlock FontSize="12" Foreground="White">
<TextBlock.Text>
<Binding XPath="Summary"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</StackPanel.Resources>
<TextBlock FontSize="18" FontWeight="Bold" Margin="10" HorizontalAlignment="Center">Data From XML</TextBlock>
<ListBox Width="200" Height="300" Background="SteelBlue" ItemsSource="{Binding Source={StaticResource BookData}, XPath=Book}" ItemTemplate="{StaticResource BookDataTemplate}"/>
</StackPanel>
Note :
You can put the Xml file in same location of xaml file. If you have external path means you should specify the path of xml file in source(Ex : Source ="data\bookdata.xml" attribute of XmlDataProvider tag.
Example 2:
This sample will help you to embed directly as an XML data island within the Resources :
In the following example, the data is embedded directly as an XML data island within the Resources section. An XML data island must be wrapped in <x:XData> tags and always have a single root node, which is Inventory in this example.
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="White">
<StackPanel.Resources>
<XmlDataProvider x:Key="InventoryData" XPath="Inventory/Books">
<x:XData>
<Inventory xmlns="">
<Books>
<Book ISBN="0-7356-0562-9" Stock="in" Number="9">
<Title>XML in Action</Title>
<Summary>XML Web Technology</Summary>
</Book>
<Book ISBN="0-7356-1370-2" Stock="in" Number="8">
<Title>Programming Microsoft Windows With C#</Title>
<Summary>C# Programming using the .NET Framework</Summary>
</Book>
<Book ISBN="0-7356-1288-9" Stock="out" Number="7">
<Title>Inside C#</Title>
<Summary>C# Language Programming</Summary>
</Book>
<Book ISBN="0-7356-1377-X" Stock="in" Number="5">
<Title>Introducing Microsoft .NET</Title>
<Summary>Overview of .NET Technology</Summary>
</Book>
<Book ISBN="0-7356-1448-2" Stock="out" Number="4">
<Title>Microsoft C# Language Specifications</Title>
<Summary>The C# language definition</Summary>
</Book>
</Books>
<CDs>
<CD Stock="in" Number="3">
<Title>Classical Collection</Title>
<Summary>Classical Music</Summary>
</CD>
<CD Stock="out" Number="9">
<Title>Jazz Collection</Title>
<Summary>Jazz Music</Summary>
</CD>
</CDs>
</Inventory>
</x:XData>
</XmlDataProvider>
</StackPanel.Resources>
<TextBlock FontSize="18" FontWeight="Bold" Margin="10" HorizontalAlignment="Center">XML Data Source Sample</TextBlock>
<ListBox Width="400" Height="300" Background="SteelBlue">
<ListBox.ItemsSource>
<Binding Source="{StaticResource InventoryData}" XPath="*[@Stock='out'] *[@Number>=8 or @Number=3]"/>
</ListBox.ItemsSource>
<!--Alternatively, you can do the following. -->
<!--<ListBox Width="400" Height="300" Background="Honeydew" ItemsSource="{Binding Source={StaticResource InventoryData}, XPath=*[@Stock\=\'out\'] *[@Number>\=8 or @Number\=3]}">-->
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock FontSize="12" Foreground="Red"> <TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
Sunday, April 29, 2007
What is the future of WPF and XAML over other technologies and how may I benefitted from using these two?.
So far, all of these aspects of the user interface have been provided in different ways on Windows. For example, a developer needs to use Windows Forms to build a Windows GUI, or HTML/ASPX/Applets/JavaScript etc. to build a web interface, Windows Media Player or software such as Adobe's Flash Player for displaying video etc. The challenge for developers is certainly clear: building a coherent user interface for different kinds of clients using diverse technologies isn't a simple job.
A primary goal of WPF (originally called Avalon) is to address this challenge! By offering a consistent platform for these entire user interface aspects, WPF makes life simpler for developers. By taking a more modern approach, including support for video, animation, 2/3D graphics, and various kinds of documents, WPF can let users work with information in new ways. And by providing a common foundation for desktop clients and browser clients, WPF makes it easier to build applications that address both.
Another challenge that has long faced the creators of user interfaces stems from the different roles required for building effective interfaces. Software developers are needed to create the logic behind the interface, and Designers are required to define the interface's look and feel. Yet older technologies such as Windows Forms are focused entirely on the developer. There's no truly effective way for developers and designers to collaborate. To address this issue, WPF relies on the eXtensible Application Markup Language (XAML). An XML-based language, XAML allows specifying a user interface declaratively rather than in code. This makes it much easier for user interface design tools like MS Expression Blend (originally branded as MS Expression Interactive Designer and code named as Sparkle) to generate and work with an interface specification based on the visual representation created by a designer. Designers will be able to use such tools to create the look of an interface and then have a XAML definition of that interface generated for them. The developer imports this definition into Visual Studio, then creates the logic the interface requires.
Developers can also build a XAML browser application (XBAP) to create a remote client that runs inside a Web browser. Built on the same foundation as a stand-alone WPF application, an XBAP allows presenting the same style of user interface within a downloadable browser application. The best part is that the same code can potentially be used for both kinds of applications, which means that developers no longer need different skill sets for desktop and browser clients. The downloaded XBAP from the Internet runs in a secure sandbox (like Java applets), and thus it limits what the downloaded application can do.
Burp, GUI is a complex but an important part of the modern applications. Through WPF, the .NET Framework 3.0 presents a more complete and consistent solution to the challenges these interfaces present. The goal is to let people who create user interfaces (both developers and designers) effectively collaborate and do their jobs more expeditiously.
From the above information You could come to the conclution for below question's.
- What is WPF and XAML?
- What is the future of WPF and XAML over other technologies?.
- How may I benefitted from using these two?. How it differs from others?.
- Will it be a consistent one( For this you might get more idea from video module which is available in my last post(What Is WPF And It's Futures?).
I Hope everyone might came to the conclusion about those questions. if you want more about this topic please feel free to ask and i will post ASAP as per your requirement.
Please leave a comment and I'll cover them in my next post.
Enjoy!!!!!!!!!!!!!!!!!!!!!!!
Thursday, April 26, 2007
What Is WPF And It's Futures?
Demo application that shows off
- Controls (rich functionality, rich content model, rich styling)
- Interop with WinForms Controls
- Layout (Panels)
- Data Binding (DataTemplates)
- Vector graphics
- Text (this demo is commented out due to font licensing issues)
- Reading (FlowDocument)
- Save a FlowDocument to XPS
- Media (Video)
- 3d
- Animation throughout
Here is the link and get idea and have a fun with WPF.
Still If you have a doubt please let me know i will try to give....
Enjoy!!!! !!!!!!!!!!!!!! Have a nice day ...
Wednesday, April 25, 2007
DataBinding In WPF
<!-- Resource Area-->
<Window.Resources>
<system:String x:Key="myvar">Hi , This is Binding </system:String>
</Window.Resources>
<!-- Bind With resource -->
//Method 1 (this method will bind whole object)
<TextBlock TextContent="{StaticResource myvar}" />
//Method 2 (this will bind particular property of object). it will display lenth property value of string .
<TextBlock Content="{Binding Source={StaticResource myvar}, Path=Length}" />
For Bind With Another Elements
<TextBlock Content="{StaticBinding Path=Length, ElementName=MyBox}" />
<TextBox Name="MyBox" />
Here textblock getting changes its content while typing the content on textbox.
Type of Mode
- OneWay -From the picture label get the value from source textbox. But it wont affect textbox value while the change happens in the label.
- TwoWay - From the picture Label get the from the Source textbox and also textbox will get the reflection while the change happens in the label.
- OneTime - From the picture Label initialized from the source textbox but does not track changes .
- OneWayToSource -if target property is not packed by a dependency property while source is . In that case we can use this mode.
Thursday, April 19, 2007
Freezable Object
Freezable having Changed event to notify any changes in the object . Freezable can improve performance because it wont take more time to spend resources on changes. A Frozen Freezable can also be shared across threads. But unfrozen cant.Although the Freezable class has many applications, most Freezable objects in Windows Presentation Foundation (WPF) are related to the graphics sub-system.
Examples of types that inherit from Freezable include the Brush, Transform, and Geometry classes. Because they contain unmanaged resources, the system must monitor these objects for modifications, and then update their corresponding unmanaged resources when there is a change to the original object. Even if you don't actually modify a graphics system object, the system must still spend some of its resources monitoring the object, in case you do change it.
For example, suppose you create a SolidColorBrush brush and use it to paint the background of a button.
Button myButton = new Button();
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);
myButton.Background = myBrush;
while painting the button on the screen , the SolidColorBrush doesn't actually do the painting , the Graphics System generates fast. low-level objects for the button and the brush, and it is those objects that actually appear on the screen. If you were to modify the brush, those low-level objects would have to be regenerated. The freezable class is what gives a brush the ability to find its corresponding generated, low-level objects and to update them when it changes. When this ability is enabled, the brush is said to be "unfrozen."
A freezable's Freeze method enables you to disable this self-updating ability. You can use this method to make the brush become "frozen," or unmodifiable.Here we are checking the object can freeze or not. Then if can means we can freeze using Freeze() method.
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);
if (myBrush.CanFreeze)
{
// Makes the brush unmodifiable.
myBrush.Freeze();
}
Not every Freezable object can be frozen. To avoid throwing an InvalidOperationException, check the value of the Freezable object's CanFreeze property to determine whether it can be frozen before attempting to freeze it.
Button myButton = new Button();
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);
myButton.Background = myBrush;
// Changes the button's background to red.
myBrush.Color = Colors.Red;
This sample first set the yellow color to Button , then will get change into the Red. after when get next page refresh. But it happening immediately after rendering the button.
Freezing a Freezable
To make a Freezable unmodifiable, you call its Freeze method. When you freeze an object that contains freezable objects, those objects are frozen as well. For example, if you freeze a PathGeometry, the figures and segments it contains would be frozen too. A Freezable can't be frozen if any of the following are true.
It has animated or data bound properties. It has properties set by a dynamic resource. (See the Resources Overview for more information about dynamic resources.) It contains Freezable sub-objects that can't be frozen.
Freezing from Markup
To freeze a Freezable object declared in markup, you use the PresentationOptions:Freeze attribute. In the following example, a SolidColorBrush is declared as a page resource and frozen. It is then used to set the background of a button.
XAML
<Page xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml xmlns:PresentationOptions=http://schemas.microsoft.com/winfx/2006/xaml/presentation/options xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006 mc:Ignorable="PresentationOptions">
<Page.Resources>
<!-- This resource is frozen. -->
<SolidColorBrush x:Key="MyBrush" PresentationOptions:Freeze="True" Color="Red" />
</Page.Resources>
<StackPanel>
<Button Content="A Button" Background="{StaticResource MyBrush}">
</Button>
</StackPanel>
</Page>
To use the Freeze attribute, you must map to the presentation options namespace: http://schemas.microsoft.com/winfx/2006/xaml/presentation/options PresentationOptions is the recommended prefix for mapping this namespace:
XAML
xmlns:PresentationOptions=http://schemas.microsoft.com/winfx/2006/xaml/presentation/options
Because not all XAML readers recognize this attribute, it's recommended that you use the mc:Ignorable Attribute to mark the Presentation:Freeze attribute as ignorable:
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="PresentationOptions"
"Unfreezing" a Freezable
Once frozen, a Freezable can never be modified or unfrozen; however, you can create an unfrozen clone using the Clone or CloneCurrentValue method.
Creating Your Own Freezable Class
A class that derives from Freezable gains the following features.
- Special states: a read-only (frozen) and a writable state.
- Thread safety: a frozen Freezable can be shared across threads.
- Detailed change notification: Unlike other DependencyObjects, Freezable objects provide change notifications when sub-property values change.
- Easy cloning: the Freezable class has already implemented several methods that produce deep clones.
A Freezable is a type of DependencyObject, and therefore uses the dependency property system. Your class properties don't have to be dependency properties, but using dependency properties will reduce the amount of code you have to write, because the Freezable class was designed with dependency properties in mind. For more information about the dependency property system, see the Dependency Properties Overview which is posted by me.
Every Freezable subclass must override the CreateInstanceCore method. If your class uses dependency properties for all its data, you're finished.
If your class contains non-dependency property data members, you must also override the following methods:
- CloneCore
- CloneCurrentValueCore
- GetAsFrozenCoree
- GetCurrentValueAsFrozenCore
- FreezeCore
Enjoy!!!!!!!!!
Wednesday, April 18, 2007
Attached Properties
Reason for Attached properties:
When dealing with out Layout system, we want to provide the ability for anybody to build new Panels. Inside of those panels you should be able to put normal elements:
<my:RobPanel>
<Button />
<Button />
</my:RobPanel>
Often, the new panel will need to define a property that the user can place on the children of that panel to control how the panel arranges the children.
<my:RobPanel>
<Button RotationsPerMinute="60" />
<Button RotationsPerMinute="3"/>
</my:RobPanel>
Unfortunately that won't work. RotationsPerMinute is a newly invented property. The Button class shipped before the RobPanel was ever built and the Button class designers forgot to include this important property!
So WPF has the concept of attached properties. One class defines the property. You attach it to instances of other objects.
<my:RobPanel>
<Button Name="b1" my:RobPanel.RotationsPerMinute="60" />
<Button Name="b2" my:RobPanel.RotationsPerMinute="3" />
</my:RobPanel>
In C#.
RobPanel.SetRotatationsPerMinute(b1, 30);
int currentRotationsPerMinute = RobPanel.GetRotationsPerMinute(b1);
So if you buy the need for this extensibility, then you need to ask why is Canvas.Top and Canvas.Left modeled as an attached property, but Height and Width are modeled as normal properties.
Top and Left are modeled as attached properties because they are only respected inside of a Canvas. If I set Top or Left on a Button inside a StackPanel or DockPanel, it would have no effect.
Lets we will see an example for attached properties !
In this example i am creating new control named as MyControl with derived from Button. In which i am creating one attached property named as MyAttack.The attached property registration is like dependency property registration and for setting value we need to implement method with signature of SetPropertyName. This method should set the value for attached property using Dependencyobject.SetValue(value) method.
Code For UserControl
public class MyControl : Button
{
public static readonly DependencyProperty MyAttackProperty = DependencyProperty.RegisterAttached("MyAttack", typeof(bool), typeof(MyControl),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnMyAttackInvalidated)));
public MyControl()
{
}
public static void SetMyAttack(DependencyObject dependencyObject, bool enabled)
{
dependencyObject.SetValue(MyAttackProperty, enabled);
}
private static void OnMyAttackInvalidated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
Button b = dependencyObject as Button;
if (b != null)
{
if ((bool)e.NewValue)
{
MyControl m = new MyControl();
m.CallClick();
}
}
}
public void CallClick()
{
MessageBox.Show("Clicked");
}
}
For Accessing Attached Property :
We can simply call the created attached property using classname.propertyname from any control attributes area. Like follow's.
<Window x:Class="AttachedProp.Window1" xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml xmlns:mn="clr-namespace:AttachedProp" Title="AttachedProp" Height="300" Width="300" >
<Grid>
<Button mn:MyControl.MyAttack="true" >Click</Button>
</Grid>
</Window>
Output of this example should display messagebox with "Clicked" message after loading the button in window.
Enjoy!!!!!!
Dependency Properties
I have faced some interesting concept in WPF ,That one is Dependency Properties ,Its really sound cool.But it takes full day for me to get the complete idea. First I have tried to get the idea from some books.but I couldn't , Then I have visited some sites about DP. There i got some partial idea. Then again Book with couple of samples, Finally I got..
Its really interesting concepts in WPF.
The concept of dependency properties(what i have understood):
WPF contain window Element Tree. It consists of all the visual objects created by the program .For example iam creating 3 buttons and put them into the Grid ,then Grid into the Window. Here Window is the parent node ,grid is child node of window and buttons are child of Grid.
Visual Tree (Not a Logical Tree because Logical Tree contain all the elements like GridRowDefenitions , GridColDefenitions and Run object associated with text Block,etc..). Obviously this is not a complete visual tree because in visual tree may include visual objects that the program does not explicitly create. (Ex. Border,Background,etc..)
In WPF, if I try to change the FontSize of the window , It will change all the child elements fontsize automatically until the child element fontsize changed by explicitly, If we changed the fontsize of child element by explicitly it won't affect the original fontsize of that particular child element. But rest of the elements will get affect. This is called Dependency Properties.The interesting aspects is, In this visual tree Grid don't have a font size property even though the buttons font size will get changes,
Using this concepts we can create our own dependency properties for our custom controls. But our control class must be inherited by FrameWorkElement or UIElement class. Here fontsize isn't the only property that works like this. Allow-Drop ,IsEnabled,IsVisible,etc.. These are all UIElement class properties.
If you got! enjoy and leave your comments here!!!!!!!!!!!!!!!!!!!
Saturday, March 31, 2007
How To Create A Full Trust XBAP Application In WPF.
The Following Steps helps to produce Full trust XBAP Application.
Step 1:
Change the TargetZone of the appliction to custom. This can be done manually by hacking the .proj file or can be done in Visual Studio by going to Project Properties, going to the Security tab, and changing the dropdown to (custom).
Step 2:
Add the Unrestricted="true" attribute to the manifest of the appliction, which is located in the Properties folder. The manifest should look something like this.
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<applicationRequestMinimum>
<defaultAssemblyRequest permissionSetReference="Custom" />
<PermissionSet class="System.Security.PermissionSet" version="1" ID="Custom" SameSite="site" Unrestricted="true"/>
</applicationRequestMinimum>
</security>
</trustInfo>
</asmv1:assembly>
Step 3:
Deploy the application using the Visual Studio Publish Wizard.
Step 4:
If you want to deploy this from the web, the certificate used to sign the manifest will have to be added to the Trusted Publishers store within Internet Explorer. By default, VS generates a .pfx key when you create a Web Browser application. Of course, real deployments, a company issued certificate would be more appropriate to use. Getting a cert into the store can be done by double clicking the cert or by using the certmgr tool with the appropriate commandline switches.
For some more Idea You may try with this ...
http://windowssdk.msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_fxdeploy/html/b24a1702-8fbe-45b1-87a0-9618a0708f1d.asp?frame=true
http://www.microsoft.com/technet/prodtechnol/windowsserver2003/library/ServerHelp/2c03582f-00b2-43e5-ae1d-493894ad0fd7.mspx
Enjoy !!!!! If You couldn't get ,please leave the comment about what you want exactly and what type of exception you are getting. It will try to give solution for your problem ..
Friday, March 30, 2007
Routed Events
Raising and handling events with the WPF is based on the new XAML markup structures, and how events are routed through a tree of elements. When a XAML page contains nested controls, there are interactive complexities that never before existed in the typical .NET UI environment.‘Nested’ controls create what is known as a Logical Tree and a Visual Tree.
Application developers have been required in times past to‘Walk-the-Tree’ by raising events and/or calling methods for each logical ‘node’ within a nested hierarchy.Events in the WPF are called Routed because there is a brand new chronological process by which to handle these events. This ordered, or routed, list of events will fire in a controlled fashion, providing full view of event the most complex Visual Trees. With the advent of Routed Events in the WPF.
The complications involved with capturing a series of hierarchical events are encapsulated and simplified. Routed Events are a pipeline of event handlers that are automatically fired for a control when any of its nested controls’ events fire. This means that it performs as a self-aware component, knowing when its members are being interacted with, and providing handler logic to respond to user or system related interactions.
A FrameworkElement could possible contain other sibling and child elements, which forms a tree of elements. In the WPF, the parent element can provide information to child elements, providing usage, customization, and visibility to the potentially smaller, nested objects. "Control Composition" is a term used to describe the creation or design concepts used when creating controls and providing thought to the handling of information within the tree. It leads developers to creating better structure for controls to control and direct the logical flow of events for the tree and its members.
Types of RoutedEvents
- Tunneling
- Bubbling
- Direct
Lets we will talk about RoutedEvent in detailed manner.
In WPF application contain many elements. You can see these elements in elements tree.(Such as visual tree). The routed event model enables you to use the element tree . This routed event will route along a route after its raised .It can travel in one of two directions. Event Listeners invoke the handlers from the root element to all successive child elements along the source element , this is called tunneling . And Event Listeners invoke the handlers from the source element to all successive parent elements along the Root element , this is called Bubbling Event.
Syntax For Routed Event
public static readonly RoutedEvent eventNameEvent;
Here event name followed by the word Event(Ex: TaskEvent)
The RoutedEvent instance obtained from registration is retained as a public static readonly field member of the class EventManager.ResgisterRoutedEvent.
Initializing Routed Event.
eventName=EventManager.ResgisterRoutedEvent(“eventName”,RoutingStratagy,typeof(RoutedEventHandler),typeof(YourClass));
Note : Don't contain Event word with eventName(It should be like : Task)
RoutingStratagy
RoutingStratagy.Tunneling
RoutingStratagy.Bubling
RoutingStratagy.Direct
Add and Remove Implementations(Initializing the Actual Event (language-specific))
we should define the actual event (ex : Task) , here the value argument is the event handler.
public event RoutedEventHandler Task
{
add
{
AddHandler(TaskEvent, value);
}
remove
{
RemoveHandler(TaskEvent, value);
}
}
Use Of RoutedEvent
Group of controls together that should all interact. The parent element is a common listener for the routed event, and uses the same event handler whenever any of the controls raises a particular event.
Example :
In this example no need to write event handler for all the buttons , by using RoutedEvent can place a common Event Handler on the Parent of two buttons. (Here in windows).
Attaching and Implementing an Event Handler for a Routed Event
Attaching a handler for a routed event in an application that is created in code is also straightforward. Routed events almost always have background implementations of add and remove logic that allow the handlers to be added by a language-specific event syntaxRouted event handlers can also be attached through a helper method AddHandler.
Example of the helper method
Button b2 = new Button();
b2.Click += new RoutedEventHandler(myEvent);
void myEvent(object sender, RoutedEventArgs e)
{
//Implementaion
}
Sample For Creating Custom RoutedEvent
MyButton.cs
class MyButton :Button
{
public static readonly RoutedEvent TaskEvent = EventManager.RegisterRoutedEvent("Task", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButton));
// Provide CLR accessors for the event
public event RoutedEventHandler Task
{
add { AddHandler(TaskEvent, value); }
remove { RemoveHandler(TaskEvent, value); }
}
// This method raises the Task event
void RaiseTaskEvent()
{
RoutedEventArgs newEventArgs = new RoutedEventArgs(MyButton.TaskEvent);
RaiseEvent(newEventArgs);
}
//Raise the event when the MyButton is clicked
protected override void OnClick()
{
RaiseTaskEvent();
}
}
Window1.xaml.cs
public partial class Window1 : System.Windows.Window
{
public Window1()
{
InitializeComponent();
// Creating Our Own Control for custom Routed Event
MyButton m=new MyButton();
m.Content ="Click Me";
m.Width =200;
m.Height =30;
this.Content = m;
m.Task += new RoutedEventHandler(m_Task);
}
void m_Task(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hai Iam The Routed Event For Your Button");
// dont want to route others
e.Handled = true;
//throw new Exception("The method or operation is not implemented.");
}
}
Note : Here Task event will raise when you click on the mybutton. and it will show message box with message.
Key Points
For events that should be routed events
- Declare a public static readonly field to hold your RoutedEvent object
- Declare CLR accessors for these routed events
- Declare a protected virtual void On( EventArgs e) method for subclasses to use. Call this method from your “class handler” -- EventManager.RegisterClassHandler(typeof(YourComponent), YourClassHandler).
- Routed events using RoutingStrategy.Tunnel should have names that begin with “Preview”.
- Many bubbling events don’t have corresponding tunnelling events, but almost all tunnelling events should have corresponding bubbling events.
- A tunnelling event should be raised before its corresponding bubbling event. If the tunnelling event was marked as handled, the bubbling event should be marked as handled before the event is raised.
Still If You Cant Get, Try with this ....
http://msdn2.microsoft.com/en-us/library/ms742806.aspx
http://blogs.msdn.com/nickkramer/archive/2005/08/15/451641.aspx
Enjoy!!!!!!!!!!!!!
Thursday, March 22, 2007
Layouts In WPF
panel themselves are responsible for sizing ans positioning elements based on different layout models.
Type of Layout :(every layout derived from Panel Class)
- DockPanel
- Grid
- StackPanel
- UniformGrid
- WrapPanel
Panel defines a property names Children used to store the child elements. Children object can be UICollection. Like image,shape,textblock and control objects.
1.StackPanel
Its used to arrange the controls vertically or horizontal stack.
XAML
<StackPanel>
<Button> </Button>
<TextBlock> < /TextBlock>
</StackPanel>
C#
StackPanel s=new StackPanel();
Button b=new Button();
b.Content=”Click”;
TextBlock t=new TextBlock();
t.Content=”run”;
s.Children.Add(b);
s.Children.Add(t);
Orientation Property
We can specify the children orientation using Orientation property of StackPanel. s.Orientation=Orientation.Horizontal;
Vertical and Horizontal Alignment
s.HorizontalAlignment=HorizontalAlignment.Horizontal (or) s.VerticalAlignment=VerticalAlignment.Vertical
2.WrapPanel
WrapPanel is similar to the StackPanel but in the WrapPanel Child elements can wrap to the next column or row automatically if there is not enough room. WrapPanel is used to add unknown number of controls like Non-Detail view in WindowsExplorer. And also we can set ItemHeight and ItemWidth properties that we can use to enforce uniform height or width, Orientation Property is same as StackPanel.
WrapPanel s=new WrapPanel();
s.ItemHeight=100;
s.ItemWidth=100;
s.Orientation=Orientation.Vertical;
Button b=new Button();
b.Content=”Click”;
TextBlock t=new TextBlock();
t.Content=”run”;
s.Children.Add(b);
s.Children.Add(t);
3.DockPanel
use of the dockpanel is automates the positioning of elements against the inside edges of their parents. We can create dockpanel in C# Like Follows.
DockPanel d=new DockPanel();
And we can set dockpanel object into the window content property.
Windowobject.Content=d;
now window layout begin with dockpanel and then we can add other type panel or control like that . Adding children in dock panel is same syntax as with other panels.
Dock.Children.Add(ctl)
But with that we need to specify on which side of the DockPanel you want control docked.
Example if you want dock the control on right side of panel you need to specify like this .
DockPanel.SetDock(ctrl,Dock.Right);
SetDock is a static method of DockPanel Class. Argument should be control and dock style.
Dock Enumeration
Dock.Right
Dock.Bottom
Dock.Top
Note :
SetDock Method call may come before or after adding the control into the panel.
Another Method for setting Dock for the control
Using attached property concept like follows.
Controlobject.SetValue(DockPanel.DockProperty,Dock.Right);
The last control is not docked at all but occupies the leftover interior space. This behavior is by default true setting of the DockPanel property LastChildFill. If we set LastChildFill=false means the last control also docked. And leftover space is unfilled .
4.Grid
its used to hosts the children in a grid of rows and columns. It has property named ShowGridLines. Its used to display the grid lines. GridLenth() is used to specify the Grid Height and Width. Constructor will take two arguments – one is value and another one is GridUnitType.
Example
GridLenth glen=new GridLength(100,GridUnitType.Pixel);
Type Of GriUnit :
GridUnitType.Auto
GridUnitType.Star
GridUnitType.Pixel
Example
Grid g=new Grid();
RowDefinition rdef=new RowDefinition();
rdef.Height=GridLength.Auto;
g.RowDefinitions.Add(rdef);
RowDefinition rdef1=new RowDefinition();
rdef1.Height=GridLength.Auto;
g.RowDefinitions.Add(rdef1);
ColumnDefinition cdef=new ColumnDefinition();
cdef.Width=GridLength.Auto;
g.ColumnDefinitions.Add(cdef);
ColumnDefinition cdef1=new ColumnDefinition();
cdef1.Width=GridLength.Auto;
g.ColumnDefinitions.Add(cdef1);
Adding Control into the Grid.
g.Children.Add(ctrl);
Grid.SetRow(ctrl,rowno);
Grid.SetColumn(ctrl,colno);
Adding RowSpan and ColumnSpan
Grid.SetRowSpan(ctrl,noofrow);
Grid.ColumnSpan(ctrl,noofcol);
5.UniformGrid
its similar to the Grid . Except that all the rows and columns are equal Height and Width.