WPF Forum FAQs - Updated for WPF 4
Locked
-
1. července 2010 14:39
I am excited to announce the availability of the following FAQ paper which lists some of the WPF 4 questions frequently asked in the forum. This version has covered many parts of the new WPF 4 features; however, it’s far from complete. We’re working on the second part which will be updated here soon. Our forum support team keeps trying to help WPF developers to find the answers to their questions even easier and faster, and it’s always the top priority for our team to make the MSDN forum a better place for developers to ask questions, talk about technologies etc. So we really welcome and appreciate any feedbacks or suggestions on how to improve the FAQ section.
On behalf of the forum support team, I want to thank Colin Eberhardt, Charles Petzold and Pete Brown from the community for their great contributions to the online WPF contents we referred to in the FAQs; thanks to the WPF team (Rob Relyea, Troy Martez, Chango Valtchev, Andre Needham, William Han, Lester Lobo and many others) for reviewing the FAQs. Finally I want to thank all the WPF forum members who actively participate in this forum and help others.
The previously published FAQs (June 2008) are available here:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a2988ae8-e7b8-4a62-a34f-b851aaf13886TOC
1. New Controls
1.1 Introduction to DataGrid, DatePicker, Calendar
1.2 How to get the cell content from Datagrid?
2. Visual State Manager
2.1 Introduction to Visual State Manager (VSM)
2.2 What is Visual State Manager, and how to use VSM to control the VisualState in the behind code?
3. Touch and Manipulation
3.1. How to use Touch and Manipulation by WPF 4?
3.2. How to use gesture in WPF4?
4. Graphics and Animations
4.1. What is Layout Rounding and how to use it in WPF 4?
4.2. What is the difference between the BitmapCacheBrush and the VisualBrush?
4.3. What is Pixel Shader 3 and how to use it in WPF 4?
4.4. How to create and use an Easing Function?
4.5. Why does Visual Studio give me a compiler warning when I use BitmapEffect classes?
5. Text
5.1. How to use the TextFormattingMode, TextRenderingMode and TextHintingMode properties?
5.2. How to change the Selection and Caret style?
6. Binding
6.1. What is a Dynamic Object and how to bind a Dynamic Object in WPF 4?
6.2. KeyBinding/MouseBinding frozen?
7. XAML Browser Applications
7.1. How to access the host page's HTML DOM from XBAP?
8. WPF and Windows
8.1. How to use the Windows 7 new taskbar features in WPF?
9. WPF and Silverlight Designer
9.1. What's new in the WPF & Silverlight designer and how to set it up?
Všechny reakce
-
1. července 2010 14:431. New Controls
1.1 Introduction to DataGrid, DatePicker, Calendar.
WPF 4 introduces three controls from WPF Toolkit: they are DataGrid, DatePicker, Calendar. Three controls make it easier to create business applications and they are almost 100 percent compatible with the Silverlight versions. (Silverlight version: DataGrid, DatePicker, Calendar.
WindowsClient.net has two articles introduce the three controls feature walkthrough which can be applied for the controls in the WPF 4.
- DataGrid: http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-datagrid-feature-walkthrough.aspx
- DatePicker and Calendar: http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx#getstarted
- DataGrid blogs in Vincent Sibal's Blog: http://blogs.msdn.com/b/vinsibal/archive/tags/datagrid/
- From Codeproject.com: Colin Eberhardt - WPF DataGrid Practical Examples: http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx
- From MSDN Magazine: Charles Petzold - Customizing the New WPF Calendar Controls: http://msdn.microsoft.com/en-us/magazine/dd882520.aspx
-
1. července 2010 14:49
1.2 How to get the cell content from Datagrid
DataGrid is one kind of ItemsControl, so it has the Items property and the ItemContainer that wraps the item. It is different with DataGridView in Windows Forms, the DataGridRow is an item in the Items collection and the cell is wrapped in a DataGridCellsPresenter structure; so we cannot get the cell content like DataGridView.Rows.Cells. However, In WPF we can access to the element in the control through VisualTree, of cause can access the DataGridRow and the DataGridCellsPresenter in the DataGrid via VisualTree; and get the cell instance in the DataGridCellsPresenter.DataGridRow rowContainer = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(rowIndex); DataGridCellsPresenter presenter = GetVisualChild(rowContainer); DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); // ... public static T GetVisualChild<T>(Visual parent) where T : Visual { T child = default(T); int numVisuals = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < numVisuals; i++) { Visual v = (Visual)VisualTreeHelper.GetChild(parent, i); child = v as T; if (child == null) child = GetVisualChild(v); else break; } return child; } -
1. července 2010 14:532. Visual State Manager
2.1 Introduction to Visual State Manager (VSM)
Visual State is introduced in the Silverlight first, and it is introduced into WPF Toolkit continue, Microsoft Expression Blend 2.5 and later supports Visual State Manager to develop the style/template. WPF 4 introduces Visual State Manager that user can set visual states in the control template and manage to transit the states based on the different conditions. Visual State Manager class seems the Trigger in the template, but it can organize the properties of the states rationally and transit the different visual states easily through VisualTransition class.
Related articles:- WindowsClient.net - WPF Toolkit: Visual State Manager Overview: http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-visual-state-manager-overview.aspx
- Silverlight.net - Styles, Templates and Visual State Manager: http://www.silverlight.net/learn/tutorials/stylestemplatesvsm-cs/
- Expression Blend and Design blog - Visual state manager tips for design and authoring: http://blogs.msdn.com/b/expression/archive/2009/10/02/visual-state-manager-tips-for-design-and-authoring.aspx
-
1. července 2010 14:58
2.2 What is Visual State Manager, and how to use VSM to control the VisualState in the behind code
VisualStateManager class manages states and the logic for transitioning between states for controls. The VisualStateManager enables you to specify states for a control, the appearance of a control when it is in a certain state, and when a control changes states. For example, a Button might have a slightly different appearance when it is pressed than when it is not pressed. Two states that the Button defines correspond to when it is pressed ("Pressed") and when it is not ("Normal"). The appearance of a control when it is in a state is defined by a VisualState. A VisualState contains a collection of Storyboard objects that specify how the control's appearance changes when the control is in that state. You add visual states to a control by setting the VisualStateManager.VisualStateGroups attached property on the control. Each VisualStateGroup contains a collection of VisualState objects that are mutually exclusive. That is, the control is always in exactly one state of in each VisualStateGroup.
In the following sample, we can call VisualStateManager.GoToElementState, VisualStateManager.GoToState to transit the element between two states, and GetVisualStateGroups to get the VisualStateManager.VisualStateGroups attached property. Below is a sample, two buttons can transit the Ellipse between two VisualState "Normal" and "Warning":
XAML:<StackPanel> <Ellipse Name="ellipse" Width="100" Height="100" Fill="Green"> <VisualStateManager.VisualStateGroups> <VisualStateGroup Name="CommonStates"> <VisualState Name="Normal"/> <VisualState Name="Warning"> <Storyboard> <ColorAnimation To="Red" Storyboard.TargetName="ellipse" Storyboard.TargetProperty="Fill.Color"/> </Storyboard> </VisualState> <VisualStateGroup.Transitions> <VisualTransition To="Normal" GeneratedDuration="00:00:01"/> <VisualTransition To="MouseOver" GeneratedDuration="00:00:01"/> </VisualStateGroup.Transitions> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Ellipse> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <Button Name="buttonNormal" Content="Normal" Click="Normal_Click" Margin="2"/> <Button Name="buttonWarning" Content="Warning" Click="Warning_Click" Margin="2"/> </StackPanel> </StackPanel>Code:
private void Normal_Click(object sender, RoutedEventArgs e) { VisualStateManager.GoToElementState(ellipse, "Normal", true); } private void Warning_Click(object sender, RoutedEventArgs e) { VisualStateManager.GoToElementState(ellipse, "Warning", true); } -
1. července 2010 15:11
3. Touch and Manipulation
3.1. How to use Touch and Manipulation by WPF 4
In WPF 4, we have the basic touch events which we can code to: TouchDownEvent, TouchEnterEvent, TouchLeaveEvent, TouchMoveEvent, TouchUpEvent. And touch supports UIElement, UIElement3D and ContentElement. So we can handle these events and draw the shapes/elements or generate the specific operations in code to achieve the multi-touch.A simple sample.
XAML:
<Canvas x:Name="canvas" TouchDown="canvas_TouchDown" TouchMove="canvas_TouchMove" TouchUp="canvas_TouchUp"/>Code:
public MainWindow() { InitializeComponent(); shapes = new Dictionary(); } private void canvas_TouchDown(object sender, TouchEventArgs e) { var shape = CreateShape(); var origin = e.GetTouchPoint(canvas); shape.RenderTransform = new TranslateTransform(origin.Position.X - shape.RenderSize.Width / 2, origin.Position.Y - shape.RenderSize.Height / 2); shapes.Add(e.TouchDevice, shape); // Add the shape to the canvas canvas.Children.Add(shape); canvas.InvalidateVisual(); canvas.CaptureTouch(e.TouchDevice); } private void _canvas_TouchMove(object sender, TouchEventArgs e) { if (e.TouchDevice.Captured == canvas) { var shape = shapes[e.TouchDevice]; var origin = e.GetTouchPoint(canvas); shape.RenderTransform = new TranslateTransform(origin.Position.X - shape.RenderSize.Width / 2, origin.Position.Y - shape.RenderSize.Height / 2); } } private void canvas_TouchUp(object sender, TouchEventArgs e) { canvas.ReleaseTouchCapture(e.TouchDevice); canvas.Children.Remove(shapes[e.TouchDevice]); shapes.Remove(e.TouchDevice); }For manipulation, we can handle ManipulationStarted, ManipulationDelta, ManipulationStarting, ManipulationCompleted events, and handle ManipulationDelta event to respond to the transformations calculated from the finger movements. A basic sample from Anson Tsao's blog:
XAML:
<Canvas x:Name="_canvas" ManipulationStarting="_canvas_ManipulationStarting" ManipulationDelta="_canvas_ManipulationDelta"> <Rectangle IsManipulationEnabled="True" Fill="Red" Width="100" Height="100"/> </Canvas>Code:
private void _canvas_ManipulationStarting(object sender, ManipulationStartingEventArgs e) { e.ManipulationContainer = _canvas; e.Handled = true; } private void _canvas_ManipulationDelta(object sender, ManipulationDeltaEventArgs e) { var element = e.OriginalSource as UIElement; var transformation = element.RenderTransform as MatrixTransform; var matrix = transformation == null Matrix.Identity : transformation.Matrix; matrix.ScaleAt(e.DeltaManipulation.Scale.X, e.DeltaManipulation.Scale.Y, e.ManipulationOrigin.X, e.ManipulationOrigin.Y); matrix.RotateAt(e.DeltaManipulation.Rotation, e.ManipulationOrigin.X, e.ManipulationOrigin.Y); matrix.Translate(e.DeltaManipulation.Translation.X, e.DeltaManipulation.Translation.Y); element.RenderTransform = new MatrixTransform(matrix); e.Handled = true; }We can refer to the following resources:
- MDSN sample - Creating Your First Touch Application: http://msdn.microsoft.com/en-us/library/ee649090.aspx
- Jaime Rodriguez's blog - Introduction to WPF 4 Multi-touch: http://blogs.msdn.com/b/jaimer/archive/2009/11/04/introduction-to-wpf-4-multitouch.aspx
- Anson Tsao's blog - Multi-touch in WPF 4: http://blogs.msdn.com/b/ansont/archive/tags/multitouch/
-
1. července 2010 15:153.2. How to use gesture in WPF4
The answer is no, WPF 4 supports multi-touch and manipulation but not gesture. We have to write a custom GestureHandler assembly and add a reference to this assembly in the WPF 4 application to support gesture. Please refer to Windows 7 Multitouch .NET Interop Sample Library to create an assembly supports gestures. The following resources are about developing Multi-touch application in Windows 7.
- MDSN sample - Creating Your First Touch Application: http://msdn.microsoft.com/en-us/library/ee649090.aspx
- Channel9 - Windows 7: Developing Multi-touch Applications: http://channel9.msdn.com/pdc2008/PC03/
- And Windows Touch Developer Resources can help us to develop a Multi-touch application in windows: http://code.msdn.microsoft.com/WindowsTouch/Release/ProjectReleases.aspxReleaseId=2127
Related thread: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/18695b90-1819-41c4-bbac-277ac2642ec5 -
1. července 2010 15:18
4. Graphics and Animations
4.1. What is Layout Rounding and how to use it in WPF 4
When an object edge falls in the middle of a pixel device, the DPI-independent graphics system can create rendering artifacts, such as blurry or semi-transparent edges. Previous versions of WPF included pixel snapping to help handle this case. Silverlight 2 introduced layout rounding, which is another way to move elements so that edges fall on whole pixel boundaries. WPF now supports layout rounding with the UseLayoutRounding attached property on FrameworkElement. Drawing objects on pixel boundaries eliminates the semi-transparent edges that are produced by anti-aliasing, when an edge falls in the middle of a device pixel. When you use layout rounding, the layout system creates small variations in the column or row measurements to avoid sub-pixel rendering.The following code uses UseLayoutRounding attached property set on a single pixel-width line. You can see the difference that layout rounding makes when you resize the window slowly.
<StackPanel Width="150" Margin="7" Orientation="Horizontal"> <!-- Single pixel line with layout rounding turned OFF.--> <Rectangle UseLayoutRounding="False" Width="45.6" Margin="10" Height="1" Fill="Red"/> <!-- Single pixel line with layout rounding turned ON.--> <Rectangle UseLayoutRounding="True" Width="45.6" Margin="10" Height="1" Fill="Red"/> </StackPanel>
-
1. července 2010 15:20
4.2. What is the difference between BitmapCacheBrush and VisualBrush
BitmapCacheBtush can allow painting an area with cached content. BitmapCacheBtush is similar to VisualBtush, sometimes we can use BitmapCacheBtush to replace to VisualBtush. Below sample is use BitmapCacheBtush and VisualBtush to draw a rectangle:<StackPanel Orientation="Horizontal"> <Rectangle Width="100" Height="25" Margin="10"> <Rectangle.Fill> <VisualBrush> <VisualBrush.Visual> <StackPanel Orientation="Horizontal"> <TextBlock Text="Hello world!"/> <Button Content="Button"/> </StackPanel> </VisualBrush.Visual> </VisualBrush> </Rectangle.Fill> </Rectangle> <Rectangle Width="100" Height="25" Margin="10"> <Rectangle.Fill> <BitmapCacheBrush> <BitmapCacheBrush.Target> <StackPanel Orientation="Horizontal"> <TextBlock Text="Hello world!"/> <Button Content="Button"/> </StackPanel> </BitmapCacheBrush.Target> <BitmapCacheBrush.BitmapCache> <BitmapCache SnapsToDevicePixels="True" RenderAtScale="2"/> </BitmapCacheBrush.BitmapCache> </BitmapCacheBrush> </Rectangle.Fill> </Rectangle> </StackPanel>However, the BitmapCacheBtush always renders from a cache of the target element or a cache defined by the BitmapCache property and the BitmapCacheBtush class ignores the following properties on the root Visual: VisualOffset, VisualTransform, VisualClip, VisualEffect, VisualOpacity, VisualOpacity. This behavior differs from the VisualBtush class.
-
1. července 2010 15:26
4.3. What is Pixel Shader 3 and how to use it in WPF 4
WPF4 builds on top of the ShaderEffect support to allow application to create custom bitmap effect using Pixel Shader 3. The Pixel Shader is a type of shader program, often executed on a graphics processing unit. These programs are typically used to perform complex per-pixel effects. Microsoft's DirectX supports shaders and DirectX 9.0c starts to support Pixel Shader version 3 which allows for even more effects on supported hardware.If a valid Pixel Shader 3 shader is loaded on a computer that does not have hardware support for Pixel Shader 3, the shader is ignored. If the shader is invalid, no exception is thrown. If a computer has more than one video card, the behavior is defined by the least capable video card. Pixel Shader 2.0 shaders run when rendering in software. However, even if Pixel Shader 3 is supported by the system's hardware, Pixel Shader 3 shaders do not run during software rendering. More information about Pixel Shader, we can refer to Fundamentals of Pixel Shaders at Gamedev.net: http://www.gamedev.net/columns/hardcore/dxshader3/
In WPF 4, we can first to create a custom effect using Pixel Shader 3 by a language called High Level Shading Language (HLSL), and use the Direct3D shader compiler fxc.exe compiles the HLSL code into byte-code, which is then executed by the runtime. Create a PixelShader to load the byte-code and wrap the effect to a ShaderEffect class in WPF, then we can set the Effect property of the UIElement to apply the custom Pixel Shader.
The following resources can help us to understand more about Pixel Shader 3 in WPF and HLSL language:
- René Schulte’s blog - Introduction to Silverlight and WPF Pixel Shaders: http://blogs.msdn.com/b/coding4fun/archive/2010/05/25/10014965.aspx
- Wikipedia.org - High Level Shader Language: http://en.wikipedia.org/wiki/High_Level_Shader_Language
- Code Plex - Windows Presentation Foundation Pixel Shader Effects Library: http://wpffx.codeplex.com/
-
1. července 2010 15:274.4. How to create and use an Easing Function
Easing functions let you control the animations with math formulas, so you can make acceleration & deceleration realistic, or apply special effects like bouncing to the animations.
The blog post Add easing effects on your animations with WPF 4 easing functions by Maxime Lamure demonstrates how to use an easing function.
In the Introduction to Easing Functions in WPF 4, Pete Brown walks us through the basics of using the easing functions.
WPF 4 has 11 built-in easing functions in the Sytem.Windows.Media.Animation namespace. You can find a list of these easing functions here.
To create your own custom easing functions, you can use the EasingFunctionBase Class as the base class. -
1. července 2010 15:29
4.5. Why does Visual Studio give me a compiler warning when I use BitmapEffect classes
BitmapEffects are deprecated.The BitmapEffect class and the classes that inherit from BitmapEffect, while still present, are disabled. The effect will render by using the hardware-accelerated rendering pipeline if the following conditions are met:
- The application uses a DropShadowBitmapEffect or a BlurBitmapEffect that has a radius property set less than 100 DIU
- The video card on the computer that runs the application supports pixel shader 2.0.
If these conditions are not met, the BitmapEffect will have no effect.
Also, Visual Studio will produce a compiler warning when it encounters BitmapEffect or a subclass.
The DrawingContext.PushEffect method is marked obsolete.
Suggested Modifications: Discontinue using the legacy BitmapEffect and derived classes and instead use the new classes derived from Effect: BlurEffect, DropShadowEffect, and ShaderEffect.
You can also create your own effects by inheriting from ShaderEffect.
-
1. července 2010 15:30
5. Text
5.1. How to use the TextFormattingMode, TextRenderingMode and TextHintingMode properties
WPF 4 has a new text rendering stack. The TextOptions class provides these three attached properties to let you control the way text is displayed in an element.The blog post WPF 4.0 Text Stack Improvements by the WPF text team has the usage of these attached properties well explained.
-
1. července 2010 15:315.2. How to change the Selection and Caret style
Before WPF 4 there are only hacks to achieve this. In WPF 4, you can specify the brush that paints the selection and caret for input and reading controls, such as TextBox, RichTextBox and FlowDocumentReader. This is achieved via the SelectionBrush Property and CaretBrush Property of the TextBoxBase Class. -
1. července 2010 15:32
6. Binding
6.1. What is a Dynamic Object and how to bind a Dynamic Object in WPF 4
Dynamic objects expose members such as properties and methods at run time, instead of in at compile time. This enables you to create objects to work with structures that do not match a static type or format.WPF 4 supports dynamic objects as binding sources. You can bind to available properties and indexers of an object that implements the IDynamicMetaObjectProvider interface (the DynamicObject implements this interface). If you can access the member in code, you can bind to it.
For permission requirements in dynamic objects data binding, please refer to this table:
http://msdn.microsoft.com/en-us/library/ms743643.aspx#permissions -
1. července 2010 15:346.2. KeyBinding/MouseBinding frozen
In WPF 4, InputBinding inherits from Freezable instead of DependencyObject. A class level InputBinding is now frozen when it is registered (CommandManager.RegisterClassInputBinding) instead of remaining mutable. -
1. července 2010 15:35
7. XAML Browser Applications
7.1. How to access the host page's HTML DOM from XBAP
When an XBAP is hosted in an HTML frame, you can now get access to the HTML window object, custom script functions and global variables via the BrowserInteropHelper.HostScript property.Please refer to WPF XAML Browser Applications Overview - Communicating with the Host Web Page for more details.
Also, refer to Lester Lobo's blog post Script Interop in Xbap for more samples.
-
1. července 2010 15:36
8. WPF and Windows
8.1. How to use the Windows 7 new taskbar features in WPF
The System.Windows.Shell Namespace contains classes that enable you to use the new Windows 7 taskbar features, for example, setting taskbar icon overlays, customize the jump list, customize the taskbar thumbnail & thumbnail buttons, etc.The "How Do I" videos by Pete Brown on WindowsClient.NET demonstrate the basic use of the new taskbar features:
How Do I: Implement Windows 7 Taskbar Icon Overlays with WPF 4
How do I: Use Windows 7 Taskbar Progress Reporting from WPF 4 -
1. července 2010 15:36
9. WPF and Silverlight Designer
9.1. What's new in the WPF & Silverlight designer and how to set it up
In Visual Studio 2010, various designer improvements have been made to help create WPF or Silverlight applications.A blog post Setting Up Visual Studio for WPF and Silverlight Development by Karl Shifflett well explained the setup of the designer environment, and introduced every element on the designer about its functionalities.