CoreCLR's Blog

Archive for the ‘WPF’ Category

Silverlight 4 Beta

Posted by coreclr on November 18, 2009

Today we can download a beta version of Silverlight 4.

The tools are here and Expression Blend are here.

Silverlight 4 has a lot of nice features. If you have done any LOB WPF development, you will be very happy to see these new features in Silverlight 4:

– Trusted applications (COM Interop, file-access, network)
– Printing Support
– Right-click context menu
– Clipboard access Support
– Better Data Binding support (grouping/editing, StringFormat)
– Implicit Styling
– RichTextbox support
– IDataErrorInfo support
– Build-in mouse wheel support
– Webcam and microphone support
– Network credentials support (authentication)
– WCF NetTcp Binding
– UDP Multicast Support
– Profiler and Profiler API
– Out of browser Window settings (position, size, chrome)
– Notification windows (toast)
– Embedding HTML (WebBrowser control)
– Same compiled code to be run on the desktop and Silverlight

and off course WCF RIA Services

This page describe all the new features and this page describe known bugs in Silverlight 4.

And finally this page describe a Technical Feature Overview.

Advertisements

Posted in .NET, Silverlight, WPF | Leave a Comment »

RelativeSource Binding in Silverlight 3

Posted by coreclr on November 9, 2009

Silverlight 3 introduced the RelativeSource Binding that we know from WPF.

As the name indicates, RelativeSource  is used when setting up a relative Data Binding.

Lets look at an example. If we want to bind the ToolTip to  Content property on the same element, we can say:

<Button Content="Button" Height="25" Width="75"
    ToolTipService.ToolTip="{Binding Content, 
RelativeSource={RelativeSource Self}}" />

As you can see, when binding to ourself, we don’t need any name on the element.

Another option is to use TemplatedParent.

Lets say that we want to change a Slider template to include a TextBox. And that TextBox should always display the same value as the slider.

Here is the full code:

<Slider Height="84" Margin="229,151,200,0" VerticalAlignment="Top">
    <Slider.Template>
        <ControlTemplate>
            <Grid x:Name="Root">
                <Grid.Resources>
                    <ControlTemplate x:Key="RepeatButtonTemplate">
                        <Grid x:Name="Root" Opacity="0" 
                              Background="Transparent"/>
                    </ControlTemplate>
                </Grid.Resources>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="CommonStates">
                        <VisualState x:Name="Normal"/>
                        <VisualState x:Name="MouseOver"/>
                        <VisualState x:Name="Disabled"/>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
                <StackPanel>
                    <Grid x:Name="HorizontalTemplate" 
                          Background="{TemplateBinding Background}">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Rectangle x:Name="TrackRectangle" 
                                   Fill="#FFE6EFF7" Stroke="#FFA3AEB9" 
                                   StrokeThickness="{TemplateBinding BorderThickness}" 
                                   RadiusX="1" RadiusY="1" Height="3" Margin="5,0,5,0" 
                                   Grid.Column="0" Grid.ColumnSpan="3"/>
                        <Rectangle x:Name="HorizontalTrackRectangleDisabledOverlay" 
                                   Fill="White" RadiusX="1" RadiusY="1" Height="3" 
                                   Margin="5,0,5,0" Opacity=".55" Visibility="Collapsed" 
                                   Grid.Column="0" Grid.ColumnSpan="3"/>
                        <RepeatButton x:Name="HorizontalTrackLargeChangeDecreaseRepeatButton" 
                                      Height="18" IsTabStop="False" Template="{StaticResource 
                            RepeatButtonTemplate}" Grid.Column="0"/>
                        <Thumb x:Name="HorizontalThumb" Height="18" Width="11" IsTabStop="True" 
                               Grid.Column="1"/>
                        <Rectangle x:Name="ThumbDisabledOverlay" Fill="White" RadiusX="2" 
                                   RadiusY="2" Width="11" Opacity=".55" Visibility="Collapsed" 
                                   Grid.Column="1"/>
                        <RepeatButton x:Name="HorizontalTrackLargeChangeIncreaseRepeatButton" 
                                      Height="18" IsTabStop="False" 
                                      Template="{StaticResource RepeatButtonTemplate}" 
                                      Grid.Column="2"/>
                    </Grid>
                    <TextBox Width="200" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                        Path=Value}"/>
                </StackPanel>
            </Grid>
        </ControlTemplate>
    </Slider.Template>
</Slider>

The line that we are interested in is this:

<TextBox Width="200"
        Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
        Path=Value}"/>

The TextBox is inside the Slider Template. We use TemplatedParent to bind the Text Property of the TextBox to it’s parent’s Value property (the slider is the parent).

There is a important difference between using a Binding with RelativeSource like this, and using the normal TemplateBinding.

The TemplateBinding is a one-way binding. From the templated parent to a element inside the template. If you need binding both ways, then you should use a Binding with RelativeSource as above.

WPF has two other options that Silverlight don’t: PreviousData and FindAncestor.

With PreviousData we can bind the previous data item in the list of data items being displayed. And FindAncestor refers to the ancestor in the parent chain of the data-bound element

Posted in .NET, Silverlight, WPF | Leave a Comment »

Debugging Release Builds

Posted by coreclr on October 30, 2009

This is a nice little trick you might not know.

Lets say you have an application build in release
mode (/debug:pdbonly /optimize+) and you want to attach the debugger directly to a running instance.

To keep it simple, this is our app:

public partial class Window1 : Window
      {
          public Window1()
          {
              InitializeComponent();
          }

          private void button1_Click(object sender, RoutedEventArgs e)
          {
              Cal(100);
          }

          int Cal(int x)
          {
              return x * x;
          }
      }

We set a break point in this line and attach to the process:

return x * x;

But the debugger will never break in our code!

The reason is that the JIT compiler has inlined the method call (remember that will compiled with /optimize+)

This is indeed a good thing. In most cases, we want the JIT compiler to have the option to inline our production code.

We can see that the module is optimized in the modules window in VS:

 image

Disable JIT Optimization

For debugging purposes, we can actually disable JIT Optimization without rebuilding the code.

Put an ini file (yes ini) in the same folder as the exe file. The filename should match the exe filename, just with ini as extension. In this case WpfApplication1.exe and WpfApplication1.ini.

The ini file should contain these 3 lines:

[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0

This will tell the JIT compiler not to optimized the code, so the method-call won’t be inlined.

We can now see that the loaded module is not optimized:

image

Remember to disable “Enter Just My Code” in VS.NET (Tools –> Options –> Debugger)

Posted in .NET, Debugging, Visual Studio, WPF | Leave a Comment »

Multiple ResourceDictionary’s with Blend Support

Posted by coreclr on October 29, 2009

On any real WPF/Silverlight project, you end up with a lot of Styles/Templates. The recommended approach is to put these in a separate ResourceDictonary.

But pretty soon, this ResourceDictonary can become very large, so we need to split it into multiple ResourceDictonary’s, but at the same time we don’t want to loose Blend Design Support.

Lets say we have a Style for ComboBox and a Style for a Button. Both styles are Based on another Style called BaseStyle. Here is a snippet of the Styles:

<Style x:Name="BaseStyle" TargetType="Control">
           <Setter Property="FontSize" Value="20" />
       </Style>


       <Style x:Key="ComboBoxStyle" TargetType="ComboBox" BasedOn="{StaticResource BaseStyle}">
           <Setter Property="Padding" Value="6,2,25,2"/>
           <Setter Property="Background" Value="#FF1F3B53"/>
           <Setter Property="HorizontalContentAlignment" Value="Left"/>
           <Setter Property="BorderThickness" Value="1"/>
           <Setter Property="TabNavigation" Value="Once"/>
           </Setter>
       </Style>

       <Style x:Key="ButtonStyle" TargetType="Button" BasedOn="{StaticResource BaseStyle}">
           <Setter Property="Background" Value="#FF1F3B53"/>
           <Setter Property="Foreground" Value="#FF000000"/>
           <Setter Property="Padding" Value="3"/>
           <Setter Property="BorderThickness" Value="1"/>
       </Style>

As long as these Styles exist in the same ResourceDictonary, then everything is good.

Now lets say we want to put the Button Style in a ResourceDictonary called ButtonResources.xaml and the ComboBoxStyle in a ResourceDictonary called ComboBoxResources.xaml.

But what do we do about the BaseStyle? We don’t want to duplicate it in both files.

One way is to create a new ResourceDictonary (BaseResources.xaml) and place it in that ResourceDictonary.

But now we lost Design-time support in Blend…

The trick here is pretty simple: just include BaseResources.xaml in both ButtonResources.xaml and ComboBoxResources.xaml:

Put this section just before the Styles in both files:

<ResourceDictionary.MergedDictionaries>
           <ResourceDictionary Source="BaseResources.xaml" />
       </ResourceDictionary.MergedDictionaries>

(Please note that you cannot have circular reference).

In our Main app we can just include the two files and everything runs:

<ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source="/SilverlightThemes;component/Themes/ButtonResources.xaml" />
         <ResourceDictionary Source="/SilverlightThemes;component/Themes/ComboBoxResources.xaml" />
     </ResourceDictionary.MergedDictionaries>

Posted in .NET, Blend, Silverlight, WPF | Leave a Comment »

Routed event handler in Silverlight 3

Posted by coreclr on October 11, 2009

In WPF its possible to add an routed event handler for a routed event. This is useful in scenarios where you want the event to bubble up the tree, even if a control marks the event as handled.

This feature is now supported in Silverlight 3 as well.

Let me give a concrete example on this feature.

Say we have a ContentPresenter when we can place any content inside. When the user click on the content, we want to catch that event (MouseLeftButtonUpEvent). But we don’t want to subscribe to each control inside the ContentPresenter.

The good news is that most event will bubble up the tree. The bad news is that some controls catches the MouseLeftButtonUp event and mark it as handled.

This is the XAML:

<Grid x:Name="LayoutRoot">
        <ContentPresenter x:Name="presenter">        
            <Border Margin="8" 
                    BorderBrush="#FFF60606" 
                    BorderThickness="2"
                    Height="100" 
                    Background="White" 
                    HorizontalAlignment="Left" 
                    VerticalAlignment="Top" 
                    Width="150">
                <Button Margin="25"                        
                        Content="Button"/>
            </Border>
        </ContentPresenter>        
    </Grid>

To catch the MouseLeftButtonUp Event on any element inside the ContentPresenter, we can now in Silverlight 3 use the AddHandler method. This is the signature:

public void AddHandler(RoutedEvent routedEvent, 
    Delegate handler, 
    bool handledEventsToo);

Add we use it like this:

public SilverlightControl1()
{
  InitializeComponent();

  this.AddHandler(UIElement.MouseLeftButtonUpEvent,
   new MouseButtonEventHandler(OnMouseLeftButtonUp), true);
}

private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
  //do stuff
}

Because we pass true as the last parameter, we indicate that we want to be invoked, even if the event has been marked as handled. In the above example, the button will handle the MouseLeftButtonUp event, so we need to pass true to the AddHandler to get invoked.

According to the doc, this feature can only be used with KeyDown, KeyUp, MouseLeftButtonDown and MouseLeftButtonUp.

Posted in .NET, Silverlight, WPF | Leave a Comment »

Exam 70-502: WPF

Posted by coreclr on September 19, 2009

I am going to write a series of blog post that describe how to learn WPF and pass the 70-502 certification.

The best way to really learn WPF is to read the documentation and read these four books 1, 2, 3, 4 (combined with real world hands-on experience).

The skills being measured at the 70-502 exam is organized in 6 main sections:

Creating a WPF Application

  • Select an application type
    May include: Choose between Windows application, Navigation application, and XAML Browser Application (XBAP) application; select the right type of application based on security restrictions
  • Configure Event Handling
    May include: tunneling vs. bubbling events; using the Event Manager class; handle application-level events
  • Configure commands
    May include: defining commands; associating commands to controls; creating custom commands; handling commands
  • Configure page-based navigation
    May include: defining and using PageFunction; using Navigation Service and hyperlinks; simple navigation vs. structured navigation; using the Journal; handling navigation events
  • Configure application settings
    May include: create application settings; create user settings; loading and saving settings
  • Manage application responsiveness
    May include: implement asynchronous programming patterns; marshalling between threads; freezing UI elements

Building User Interfaces

  • Select and configure content controls
    May include: applying attached properties of controls to a user interface element; selecting appropriate controls for specific uses
  • Select and configure item controls
    May include: using lists, toolbars, menus, tree views, virtualization of item controls, status bar
  • Select and configure layout panels
    May include: choosing the correct layout panel; configuring sizing; aligning content; using a grid splitter
  • Integrate Windows Forms controls into a WPF application
    May include: adding controls not available in WPF, such as the property grid and masked text box; interop dialog boxes
  • Create user and custom controls
    May include: render appearance based on currently selected system theme; incorporate accessibility features by using UI automation; choosing between custom controls, user controls, and templates; consuming user control or custom controls; creating and handling routed events

Adding and Managing Content

  • Create and display two dimensional and three dimensional graphics
    May include: using geometric transformation; brushes; drawing shapes; clipping; flipping; hit testing
  • Create and manipulate documents
    May include: XML Paper Specification (XPS) and flow documents; incorporating UI elements inside documents; choosing the right element for text presentation; scaling text; selecting controls for formatting text documents; printing
  • Add multimedia content
    May include: media player vs. media element; adding a sound player; handling media-specific events such as buffering
  • Manage binary resources
    May include: embedding resources in your application; linking to external resources; preloading resources; asynchronously using resources; sharing resources
  • Manage images
    May include: accessing image metadata; transforming graphics into images; stretching and sizing images

Binding to Data Sources

  • Configure binding options
    May include: setting the correct binding mode and update mode; using static resources; using dynamic resources
  • Bind to a data collection
    May include: filtering, sorting, and grouping data; using data templates; binding to hierarchical data; binding to objects
  • Bind to a property of another element
    May include: using template binding; binding to an ancestor property
  • Convert and validate data
    May include: localizing data; using custom converters and custom validators; using multivalue converters
  • Configure notification of changes in underlying data
    May include: implementing INotifyPropertyChanged; using ObservableCollection

Customizing Appearance

  • Create a consistent user interface appearance by using styles
    May include: applying a style automatically to all controls of a specific type; implementing style inheritance; property value precedence (order in which dependency property values are applied)
  • Change the appearance of a UI element by using triggers
    May include: using multiple triggers; using property triggers; using event triggers; using data triggers
  • Add interactivity by using animations
    May include: creating a storyboard; controlling timelines; controlling the behavior when the animation completes; animating non-double data types; starting an animation from code
  • Share logical resource throughout an application

    May include: choosing where to store a resource; merging resource dictionaries; retrieving a resource by using procedural code

  • Change the appearance of a control by using templates
    May include: inserting a trigger inside a template; using predefined part names in a template; respecting the templated parent’s properties
  • Localize a WPF application
    May include: loading resources by locale; marking localizable elements; using culture settings in validators and converters; using language properties and rendering direction properties

Configuring and Deploying WPF Applications

  • Deploy for standalone access
    May include: using the MSI to create the installation; using click-once installation; configuring update options
  • Deploy to a partial trust environment

    May include: choose the correct local persistence mechanism; remove or disable application features that will not work in a partial trust environment

  • Deploy an XBAP application
    May include: publish an XBAP application to a temporary location; publish an XBAP application to a final location; deployment dependencies
  • Manage upgrades
    May include: loading modules on demand; migrating settings; migrating user data; programmatically check for updates
  • Configure the security settings of an application deployment
    May include: configuring application manifest; associating certificates with the application

Over the next weeks/months, I am going to blog about each of these. So stay tuned…

Posted in WPF | Leave a Comment »

Clear/Remove a Data Binding in Silverlight

Posted by coreclr on September 1, 2009

When doing dynamic Data Bindings in code in Silverlight, we often need to clear/change the Binding on controls.

In WPF, we can use the ClearBinding methods on the BindingOperations class.
But in Silverlight, the BindingOperation Class don’t have these methods.

One way to clear a binding in Silverlight is just to use the ClearValue methods defined on the DependencyObject.
Here is a very simple example:

Person p1 = new Person1();
Person p2 = new Person2();

private void OnClick(object sender, RoutedEventArgs e)
       {
           if (this.DataContext == p1)
           {
              ClearBindings();
              this.DataContext = p2;
              t1.SetBinding(TextBox.TextProperty, new Binding("Name"));
              t3.SetBinding(TextBox.TextProperty, new Binding("Name2"));
           }
           else
           {
              ClearBindings();
              this.DataContext = p1;
              t1.SetBinding(TextBox.TextProperty, new Binding("Name"));
              t2.SetBinding(TextBox.TextProperty, new Binding("Name1"));
           }
       }
private void ClearBindings()
      {
          t1.ClearValue(TextBox.TextProperty);
          t2.ClearValue(TextBox.TextProperty);
          t3.ClearValue(TextBox.TextProperty);
      }
And here is the xaml:
<StackPanel Width="200" Height="50">
           <Button Click="OnClick" Content="Change Binding"></Button>
           <TextBox x:Name="t1" />
           <TextBox x:Name="t2" />
           <TextBox x:Name="t3" />
</StackPanel>

Posted in Silverlight, WPF | Tagged: , | Leave a Comment »