in

ExpressionBlog.com

Microsoft Expression Studio Community

This Blog

Syndication

Mirrored Blogs

Browse by Tags

All Tags » Custom Controls (RSS)
  • Custom Controls – The Dénouement

    Over the past month I've posted half a dozen min-articles about creating custom controls that can interact with the Visual State Manager, and the underlying engine that makes it work; especially Dependency Properties and the Parts and States Model . Intro to Custom Controls Part 1 Intro to Custom Controls Part 2 Creating Custom Controls Generic.xaml Dependency Properties Part 1 Dependency Properties Part 2 Dependency Property Precedence With this background, we're ready to move on to the steps of implementing visual states in your custom control. The key concept that we've been building to is this: there is a strict separation between the logic of your control, and the visuals of your control. The place that this becomes most clear is often when you click on a control. Visually, many controls respond to a click with some form of visual change. Logically they respond with some behavior- or they raise an even that allows "listeners" to respond. Keeping these separate is key to the Parts and States model. The Custom Control that we're going to create (in a whirlwind fashion here, more carefully and slowly in a forthcoming tutorial and videos) is derived from Control, draws its own shape, is designed to be skinnable, and supports the parts and states model. As such, it defines three CommonStates Normal MouseOver Pressed It also defines two CustomStates Normal On Notice that because the StateGroups (CommonStates and CustomStates) are orthogonal, there is no problem having a NormalState in both. State Changes. The custom control appears as a grey ball when it is in its Normal CommonState and in its Normal CustomState, but its visual appearance changes noticeably when it moves into any of the other states. In addition, I've added a template that changes its appearance in its normal state and in its other visual states and to cap it off the control publishes an event for when it is clicked allowing the page that houses the control (templated or not) to respond to the click. <whew!> While we'll save the nitty gritty for the tutorial and the videos, the point to focus on here is this: how does the control convey its visual contract to the Visual State Manager (and to Expression Blend?). That is accomplished using attributes . These are placed above the definition of the CustomControl and constitute the contract between the control and the Visual State Manager; they assert the state groups and the states within those state groups...
  • Silverlight Controls, Controls Team, and Testing

    This blog will rarely be the place for breaking news, but there are two related pieces of information I want to ensure you know about at the risk of repeating news that has been blogged by others.  First, Shawn Burke’s team has announced their intention to release the following new Silverlight controls at PDC 08: DockPanel WrapPanel ViewBox Label HeaderedContentControl Expander TreeView NumericUpDown AutoComplete Accordion Really more important than this list is the fact that Scott Guthrie (ScottGu) has asked one of our smartest and most productive managers, Shawn Burke to create and build the Controls Team (as Shawn explains here ). Their new release model is well worth reading about, and they have some very exciting plans for building controls that will make coding in Silverlight that much easier. I’m particularly interested in how the Label might interact with the PresentationControl, how the TreeView andExpander might interact with data in a client-only architecture and how the new layout controls will change the look and feel of Silverlight applications. More than any of that, I’m eager to set aside some time to play with the Unit Test Framework they’ve developed that Shawn introduces here ,  as that may well become a central application building tool. I highly recommend reading Jeff Willcox’s writeup of his testing tool; don’t let this slip by without taking note.   You’ll find everything you need to get started with the test tool here including additional tutorials, videos and so forth.  Enjoy   -j
  • Template Browser – an indispensible tool

    One way that many developers like to create styles and templates for controls is to modify the existing styles and templates. An unusual feature of Silverlight is that every control in the toolbox is lookless – its appearance is determined by its own generic.xaml, just like the custom controls you create. Finding this generic.xaml can be a bit tricky, as it is stored in a specially named resource file, but it is all documented on MSDN . That would be pretty good, but David Anson (aka "Delay") has created a wonderful desktop tool for inspecting (and copying) the styles and templates of the Silverlight controls (Click on image for full size) This is a really nice piece of work, allowing you to expand and collapse and spelunk the templates and styles and also to copy either or both to the clipboard to bring into your own code. I've added the circles and arrows to point out that the outline of elements is entirely collapsible and that the bottom of the browser offers a number of useful options. I find this particularly useful in finding best practices for working around apparent limitations such as the changes to the ContentPresenter discussed on Sept 28. Note that the link to the standalone tool includes the source code – but the program was written in WPF, not Silverlight. If you want the Clickonce version, you'll want this link.
  • Dependency Properties - Precedence

    Today we wrap up dependency properties by talking about one of the most important, though typically invisible aspects: DP precedence order. This is critical because dependency properties, by their nature, are designed to have their final value set from more than one influence (e.g., resources, data binding, animation, etc.) The rule is rigid, sensible and straight forward… Animation uber alles. If there is an animation affecting the value, that will take precedence over all other values Local values over everything but Animation In the absence of an animation, use the local value to override any other values Templates/Styles if no animation or local values If there is no animation or local value, use the value from the template, and if there is no template then from the style. When all else fails, use the default If none of the above apply, use the default value for that type. The Default Value It is the last rule that demands that every type have a default look, and it is because of that rule that you crated generic.xaml – so that if your custom control has a value that is not controlled by an animation, a local value, a template or a style, the Dependency Property System will turn to the default values in generic.xaml and use those. Our First Application With this, we're ready to examine the code to our first application.  As you may remember , we have three projects in one solution.  In CustomControl.cs we declare the visual logic of our control and we will, eventually declare the logic (event handlers, etc.) as well. For now, the listing is quite simple: 1: using System.Windows.Controls; 2:   3: namespace ClassLibrary 4: { 5: public class CustomControl : Control 6: { 7: public CustomControl() 8: { 9: DefaultStyleKey = typeof ( CustomControl ); 10: } 11: } 12: } The simplest logic you can add to get the default style to show. The default style, as you remember is in the file generic.xaml which in turn is in the Themes folder, 1: < ResourceDictionary 2: xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3: xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" 4: xmlns:controls ="clr-namespace:ClassLibrary" 5: xmlns:vsm ="clr-namespace:System.Windows;assembly=System.Windows" 6: xmlns:d ="http://schemas.microsoft.com/expression/blend/2008" 7: xmlns:mc ="http://schemas.openxmlformats.org/markup-compatibility/2006" 8: mc:Ignorable ="d" > 9: < Style...
  • Dependency Property System – Deeper Dive Part 1

    On the 17th I began a discussion of Dependency Properties, but as I said then, there is more to say. This central concept to Silverlight Programming has traditionally been taught as an advanced concept.(Can we have traditions in a product that hasn't really been released yet?) And to some degree, with good reason: you can pretty much ignore the Dependency Property System until/unless you're writing custom controls. Here are three reasons not to: 1. They're fascinating 2. They explain a lot about how things work 3. They are critical to creating your own custom controls Okay, the real reason is #1; they're just interesting. There are a couple ways to approach Dependency Properties. Most of us approach them practically, to accomplish a specific goal at first ("How do I wire up a DP in this custom control?") and then later, we return to understand the entire system into which they fit. It is the purpose of today's column to begin that second stage: examining the system as a whole. An Adventure in Spelunking the Dependency Properties System We need to start by acknowledging a few somewhat surprising facts: The folks who created WPF and Silverlight made some rather radical (and I would argue technically courageous) decisions: they said "the current properties are inadequate for our needs, and we're going to add a new layer on top that will not break the underlying layer but that will give us tremendous additional options." Thus, the Dependency Properties system is really a radical extension to the CLR and to that which is available in C++, Java, or even pre-WPF C#/VB.NET. Then the folks at Silverlight chose which parts of the system they would use, which they'd adapt and which they'd leave behind based on optimizing for the needs of Silverlight rather than just for pure isomorphic consistency. Controversial but highly defensible decisions, and ones that will give us early headaches trying to understand all of it, but long term benefits. The biggest problem, of course, is that figuring out what is really going on can be a bit problematic, especially right now. This particular moment in history is a documentation purgetory. The WPF books are excellent but not everything they say applies to Silverlight The Beta2 chm file and help files are very good but now partially obsolete The change document is helpful but not guaranteed to be complete Full documentation of Dependency Properties was never a priority as it was considered...
  • Skinnable Custom Controls – Change to generic.xaml

    This is the first in a series of explorations of breaking changes in the Release Candidate for Silverlight 2. Please be sure to read Tim's blog entry about Silverlight RC0 for context and directions. Summary There are 2 significant breaking changes in how you handle the file generic.xaml when creating a Skinnable custom control in Silverlight 2. This is a change from my blog post on 21st of September and the 12th of September and will be reflected in the forthcoming videos and tutorial. The first change is that the file itself has a new location inside the Themes folder. The second is that the syntax has changed from declaring storyboards as resources and the referring to them in the declaration of Visual States, to combining the declaration of visual state with defining the associated storyboards. The first change makes Silverlight more WPF-like. The second change may or may not have been 100% intentional but will be in the release and I personally find it totally inoffensive. Location, Location, Location The file generic.xaml has moved in RC0 from the root of the class library to a folder named Themes: (Right click on Class Library and choose New Folder – name it Themes. Right click on the folder to choose New Item and create the user control or if you've already created it, drag it into the folder). Syntax The syntactic change is to remove the <Grid.Resources> section and to combine the definition of the Storyboards with the definition of the States. Here is the old syntax: 1: < ResourceDictionary 2: xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3: & lt ; Style TargetType ="controls:StatusControl" > 4: < Setter Property ="Template" > 5: < Setter.Value > 6: < ControlTemplate TargetType ="controls:StatusControl" > 7: < Grid x:Name ="LayoutRoot" > 8: < Grid.Resources > 9: < Storyboard x:Key ="MouseOverState" > 10: </ Storyboard > 11: < Storyboard x:Key ="OnState" > 12: </ Storyboard > 13: </ Grid.Resources > 14: < vsm:VisualStateManager.VisualStateGroups > 15: < vsm:VisualStateGroup x:Name ="CommonStates" > 16: < vsm:VisualState x:Name ="Normal" /> 17: < vsm:VisualState x:Name ="MouseOver" 18: Storyboard ="{StaticResource MouseOverState }" /> 19: </ vsm:VisualStateGroup > 20: < vsm:VisualStateGroup x:Name ="StatusStates"...
  • Creating Custom Controls – A Common Starter Application

    It will be helpful as we explore custom controls to have a common starting project. You may  remember from my posting on the 12th that I laid out a structure with three projects in one solution, with 5 important files. In the ClassLibrary, customcontrol .cs  which defines the logic and methods as well as the attributes of the custom control. The attributes define the contract, and are what make the control skinnable with the assistance of tools like Blend Also in the ClassLibrary is a file that must be named generic.xaml that defines the default look for your custom control (in xaml). In your application there are three files (as usual) that do the heavy lifting: Page.xaml, Page.xaml.cs and App.xaml .  They do their normal jobs. That is: Page.xaml makes an instance of the control and may or may not include a Template statement asking for a Template in Page.xaml or (more likely) in App.xaml to override the default look and feel Page.xaml.cs contains the logic of the application (not of the control) just as it always does App.xaml may have a template for your new Custom control just as it may have a template for button or checkbox. I've created a starter application with corresponding files and placed it here   The starter application just lays out the structure of the program and will be used for three inter-related purposes 1. An intensive tutorial (expected publication date approximately 10/13 2. A set of video I'll be developing in the next week or two 3. Blog entries exploring what I hope will be interesting topics in depth Following the suggestions received here, the tutorial should be pretty intensive, while the blog and videos will assume a more intermediate level of knowledge.  If this topic (templatable custom controls) is of interest, you'll want to start by reviewing some or all of these: Blog entries Intro To Custom Controls Digging into Custom Controls Dependency Properties - Background Tutorial Templates and Visual State Manager Videos Creating Styles Templates Templates and Blend   Thanks.
  • Dependency Properties – Background for Custom Controls

    In  a previous post I began talking about Custom Controls, and I will continue that discussion over the next few days and weeks even as I start producing videos on the topic. It turns out that the more you look at Custom Controls, the deeper you get into the Silverlight UI architecture, and there is much to see. As an example of this phenomenon, in writing about Custom Controls, you quickly realize that sooner or later you must describe and explain the Dependency Properties System in Silverlight. This brings great joy to my heart, because it is one of the more interesting and one of the less discussed aspects of Silverlight programming So this evening I'm going to leap ahead (a bit out of order) and introduce this system, though by no means cover it in depth in one blog post.  (Written late Tuesday, posted early Wednesday) Understanding Our Roots Traditional C# classes consist of Methods Events Member Variables Properties You can easily view these in the Object Browser in Visual Studio (all but the member variables, which are almost always marked private and not shown). [Note, image cut down to save space] C++  did not have properties (nor running water, nor electricity). Back in those dark days, if we wanted to provide access to the value of a member variable, we created methods to do so. Thus, you ended up with funny looking code like this: overallApproval = jesse.GetApprovalAverage() + tim.GetApprovalAverage(); Rather than the more natural, overallApproval = jesse.Approval + tim.Approval; Properties were brilliant . They looked to the class author just like methods, but they looked to the class consumer just like variables. This was crucial. The class author was free to continue to obtain the actual value from backing variables or anywhere else: 1: private double approval = .4; 2: public double Approval 3: { 4: get 5: { 6: if ( currentViewer.ID == "ScottGu" ) 7: return .9; 8: else 9: return approval; 10: } 11: } In practical experience, most properties are backed by member variables, though that is by no means universal – some are backed by values in persistent storage, and some are computed dynamically. But some very large percentage are backed by member variables, which is why Auto-implemented properties were invented (and they are also brilliant). Prior to C# 3.0 my code was peppered with annoying properties that looked like this: 1: private int myMember; 2: public int MyProperty 3: { 4: get { return myMember; } 5: set { myMember...
  • Digging Into Custom Controls

    Last night’s post was something of a preface, but let’s get started. [ For those of you who crave the details, the code, the feel of bits between your fingers, watch for a series of videos on this subject to be released in the next couple weeks with source in VB and C# ] As I started to say last night , the key distinction in writing custom controls in Silverlight as opposed to other GUI environments is the strict division between logic and visuals embodied in the Parts and States Model. As an aside, this is where we always point out that there is nothing in Silverlight that requires or enforces that you implement your custom control using the Parts and States model, but it is the model recommended by Microsoft, and it is the model understood and supported by Expression Blend. The fact is, I can’t imagine creating a custom control that does not conform to the P&S model except to show that it can be done. A Brief Introduction to the Parts and States Model The key concept behind the P&S model is that your control will have a strict separation of logic from visuals, and the visuals will be managed by the Visual State Manager which will need to know (a) what States might the control be in (states are defined in just a moment) and (b) what parts of the control might be under VSM control. States are familiar to those who’ve worked with Templates, and in truth, if you haven’t you want to stop right here and go do that. I posted three videos on styles and templates that will get you started as well as a few useful blog entries From a P&S model perspective, a control is either in a state or transitioning from one state to another. The Visual State Manager is responsible for running the storyboard associated with your control being in a given state (such as MouseOver). If you are templating an existing control, the states have been enumerated already, you can’t add new states unless you create a custom control. More on that in a moment Parts Controls are of course made up of many parts (little p) but from a P&S perspective they aren’t considered Parts unless they will be called by methods of the control itself. For example, the ScrollBar is a control available in the Silverlight toolbox. From the P&S view point it can be decomposed into four Parts. · Down Repeat Button · Up Repeat Button · Scroll Bar · Thumb While there may be other elements in a Scrollbar, these are the Parts, because these elements are the only elements that other elements of the...
  • The difference between understanding a concept…

    … and implementing it, can be the difference between your book being on time, and being, er, ah, well… late. I’ve written chapters on custom controls at least a dozen times, and I’ve explained how to write custom controls at least a hundred times. You’d think I could do it in my sleep. In this first of a series of blog entries about Silverlight custom controls I’ll try to convey why creating custom controls is not difficult, but explaining it, or at least explaining it well, is. There were custom controls in ASP.NET, in Windows Forms, in many other GUI platforms, and they’ve always been just  about the same idea. You typically had three options: Option One The first way to create a custom control is to aggregate two or more existing controls into a new type; to make something new (or something monstrous). My favorite example is to combine a button with a DropDown to make a button whose action can change.     Option Two The second approach is to derive from an existing control but to add a little new functionality. My standard  example is Clickable button, a button that knows how many times it has been clicked. The code shown below is taken from Programming ASP.NET   but the concepts are the same across many GUI frameworks.     1: using System; 2: using System.ComponentModel; 3: using System.Web.UI; 4:   5: namespace CustomControls 6: { 7: [DefaultProperty( "Text" )] 8: [ToolboxData( "<{0}:CountedButton2 runat=server></{0}:CountedButton2>" )] 9: public class CountedButton : System.Web.UI.WebControls.Button 10: { 11: private string displayString; 12:   13: public CountedButton( ) 14: { 15: displayString = "clicks" ; 16: InitValues( ); 17: } 18:   19: private void InitValues( ) 20: { 21: if (ViewState[ "Count" ] == null ) 22: ViewState[ "Count" ] = 0; 23: this .Text = "Click me" ; 24: } 25: 26: public int Count 27: { 28: get { return ( int ) ViewState[ "Count" ]; } 29: set { ViewState[ "Count" ] = value ; } 30: } 31:   32: protected override void OnClick(EventArgs e) 33: { 34: ViewState[ "Count" ] = (( int )ViewState[ "Count" ]) + 1; 35: this .Text = ViewState[ "Count" ] + " " + displayString; 36: base .OnClick(e); 37: } 38: } 39: } 40:   Option Three And the third, typically most labor-intensive approach is to derive from a root Control object and (typically) draw the entire...
Powered by Community Server (Commercial Edition), by Telligent Systems