1. Trang chủ
  2. » Công Nghệ Thông Tin

C# 2005 Programmer’s Reference - chapter 18 pptx

66 323 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Part III: User Interaction

    • 18 WPF

      • Format Values During Data Binding

      • Convert Values to a Different Type During Data Binding

      • Bind to a Collection

      • Specify How Bound Data Is Displayed

      • Define the Look of Controls with Templates

      • Animate Element Properties

      • Render 3D Geometry

      • Put Video on a 3D Surface

      • Put Interactive Controls onto a 3D Surface

      • Use WPF in a WinForms App

      • Use WinForms in a WPF Application

    • 19 ASP.NET

      • View Debug and Trace Information

      • Determine Web Browser Capabilities

      • Redirect to Another Page

      • Use Forms Authentication for User Login

      • Use Master Pages for a Consistent Look

      • Add a Menu

      • Bind Data to a GridView

      • Create a User Control

      • Create a Flexible UI with Web Parts

      • Create a Simple AJAX Page

      • Do Data Validation

      • Maintain Application State

      • Maintain UI State

      • Maintain User Data in a Session

      • Store Session State

      • Use Cookies to Restore Session State

      • Use ASP.NET Model-View-Controller (MVC)

    • 20 Silverlight

      • Create a Silverlight Project

      • Play a Video

Nội dung

ptg 382 CHAPTER 18 WPF LISTING 18.2 Window1.xaml.cs (continued) InitializeComponent(); } protected override void OnDragEnter(DragEventArgs e) { base.OnDragEnter(e); //is it a list of files? if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effects = DragDropEffects.Copy; } else { e.Effects = DragDropEffects.None; } } protected override void OnDrop(DragEventArgs e) { base.OnDrop(e); if (e.Data.GetDataPresent(DataFormats.FileDrop)) { foreach(string path in (string[])e.Data.GetData( ➥ DataFormats.FileDrop)) { //grab first image try { BitmapImage image = new BitmapImage(new Uri(path)); ImageInfoViewModel model = new ImageInfoViewModel(image); this.ImageInfo = model; } catch (Exception ) { } } } } } } From the Library of Skyla Walker ptg 383 Convert Values to a Different Type During Data Binding Here’s a part of the XAML that binds elements to the ImageInfoViewModel object: <Expander Header=”Image Info” IsExpanded=”True” x:Name=”imageInfoGroup”> <Grid DockPanel.Dock=”Left”> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Label Grid.Row=”0” Grid.Column=”0”>Filename</Label> <TextBox IsReadOnly=”True” Grid.Row=”0” Grid.Column=”1” Text=”{Binding Path=FileName, Mode=OneWay}”/> <Label Grid.Row=”1” Grid.Column=”0”>Width</Label> <TextBox IsReadOnly=”True” Grid.Row=”1” Grid.Column=”1” Text=”{Binding Path=Width, Mode=OneWay}”/> <Label Grid.Row=”2” Grid.Column=”0”>Height</Label> <TextBox IsReadOnly=”True” Grid.Row=”2” Grid.Column=”1” Text=”{Binding Path=Height, Mode=OneWay}”/> </Grid> </Expander> Every time you drag an image onto the ImageViewer application, the UI will update with information about that image automatically when the ImageInfo property is set. Format Values During Data Binding Scenario/Problem: You need to apply formatting to the bound value. Solution: Starting in .NET 3.5 SP1, you can use the StringFormat property. <TextBox IsReadOnly=”True” Grid.Row=”1” Grid.Column=”1” Text=”{Binding Path=Width, Mode=OneWay, StringFormat=N0}”/> Convert Values to a Different Type During Data Binding Scenario/Problem: You want to convert one type to another in data binding. For example, you could bind a control’s color to some text. From the Library of Skyla Walker ptg 384 CHAPTER 18 WPF Solution: Define a converter class derived from IValueConverter and implement one or both methods: class FilenameToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (string.IsNullOrEmpty(value as string)) { return Brushes.Red; } else { return Brushes.Green; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { //you only need to implement this for two-way conversions throw new NotImplementedException(); } } In your window XAML, define a resource and specify the converter where needed. In the following example, the background color is bound to the filename with this converter so that it becomes red if the filename is null: <Window x:Class=”ImageViewer.Window1” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local=”clr-namespace:ImageViewer” Title=”Image Viewer” Height=”426” Width=”537” AllowDrop=”True” Name=”MainWindow” > <Window.Resources> <local:FilenameToColorConverter x:Key=”fileColorConverter”/> </Window.Resources> From the Library of Skyla Walker ptg 385 Specify How Bound Data Is Displayed <TextBox IsReadOnly=”True” Grid.Row=”0” Grid.Column=”1” Text=”{Binding Path=FileName, Mode=OneWay}” Background=”{Binding Path=FileName, Mode=OneWay, Converter={StaticResource fileColorConverter}}”/> </Window> Bind to a Collection Scenario/Problem: Some elements display a collection of items. You want to bind this to a data source. Solution: Binding to a collection of items is fairly straightforward. You can declare XAML like this: <Expander Header=”All Properties” IsExpanded=”False” x:Name=”allPropertiesGroup”> <ListBox <! AllProperties is defined as ICollection<KeyValuePair<string, object>> in ImageInfoViewModel > ItemsSource=”{Binding Path=AllProperties}” /> </Expander> However, because WPF doesn’t know how to display each item in the collection, it’s just going to call ToString() on each item. To customize the display, you need to define a data template, which is covered in the next section. Specify How Bound Data Is Displayed Scenario/Problem: You need to control the way bound items are displayed. Solution: You can use a data template. Data templates are defined as resources: <Window.Resources> <DataTemplate x:Key=”dataItemTemplate”> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width=”80”/> <ColumnDefinition Width=”*”/> From the Library of Skyla Walker ptg 386 CHAPTER 18 WPF </Grid.ColumnDefinitions> <Label Content=”{Binding Path=Key, Mode=OneWay}” Grid.Column=”0”/> <TextBox Text=”{Binding Path=Value, Mode=OneWay}” IsReadOnly=”True” Grid.Column=”1” HorizontalContentAlignment=”Left” HorizontalAlignment=”Left” /> </Grid> </DataTemplate> </Window.Resources> Then modify the ListBox’s ItemTemplate property to refer to it: <Expander Header=”All Properties” IsExpanded=”False” x:Name=”allPropertiesGroup”> <ListBox ItemsSource=”{Binding Path=AllProperties}” ItemTemplate=”{StaticResource dataItemTemplate}” /> </Expander> The result is an attractive display of an arbitrary number of collection items, as previously seen in Figure 18.4. Define the Look of Controls with Templates Scenario/Problem: You want to set a control’s look according to one or more templates and be able to change them at runtime. Solution: If you look closely at Figures 18.3 and 18.4, you’ll see that the latter shows a caption under the image, whereas the former does not. This is accom- plished with control templates. The two ControlTemplates are defined, as usual, in the resources: <Window.Resources> <ControlTemplate x:Key=”imageTemplate” TargetType=”{x:Type ContentControl}” x:Name=”imageControlTemplate”> <Image Source=”{Binding Path=Image}” /> </ControlTemplate> <ControlTemplate x:Key=”imageWithCaptionTemplate” TargetType=”{x:Type ContentControl}”> From the Library of Skyla Walker ptg 387 Define the Look of Controls with Templates <Grid> <Grid.RowDefinitions> <RowDefinition Height=”*”/> <RowDefinition Height=”Auto”/> </Grid.RowDefinitions> <Image Source=”{Binding Path=Image}” Grid.Row=”0”/> <TextBlock Text=”{Binding Path=FileName}” HorizontalAlignment=”Center” FontSize=”16” Grid.Row=”1”/> </Grid> </ControlTemplate> </Window.Resources> And the default template is set in the element’s definition: <Window > <DockPanel> <ContentControl Template=”{DynamicResource imageTemplate}” Name=”controlDisplay”/> </DockPanel> </Window> An event handler (discussed previously) on the radio buttons causes the template to be switched: private void OnTemplateOptionChecked(object sender, RoutedEventArgs e) { if (radioButtonNoCaption != null && controlDisplay!= null) { if (radioButtonNoCaption.IsChecked == true) { controlDisplay.Template = (ControlTemplate)FindResource(“imageTemplate”); } else { controlDisplay.Template = (ControlTemplate)FindResource(“imageWithCaptionTemplate”); } } } From the Library of Skyla Walker ptg 388 CHAPTER 18 WPF Animate Element Properties Scenario/Problem: You want to change UI properties over time. Solution: As far as WPF is concerned, animation is the change of an element’s properties over time. For example, you could change the x position of a button from 1 to 100 over, say, 5 seconds. This would have the effect of moving the button on the screen during that time. You can animate any dependency property in WPF. The ImageViewer application uses a single animation to fade in the left-side panel over 5 seconds when the application starts. Figure 18.5 shows the application with it faded in about halfway. First, define the storyboard with animation in the Window’s resources: <Window.Resources> <Storyboard x:Key=”FadeInLeftPanel” Storyboard.TargetName=”LeftPanel”> <! Double refers to the Type of the property > <DoubleAnimation Storyboard.TargetProperty=”Opacity” From=”0.0” To=”1.0” Duration=”0:0:5” /> </Storyboard> </Window.Resources> Once the animation is defined, you need to start with a trigger: <Window> <Window.Resources> </Window.Resources> <Window.Triggers> <EventTrigger RoutedEvent=”Window.Loaded”> <BeginStoryboard Storyboard=”{StaticResource FadeInLeftPanel}” /> </EventTrigger> </Window.Triggers> </window> From the Library of Skyla Walker ptg 389 Render 3D Geometry FIGURE 18.5 This image shows the sidebar fading in during program startup. Render 3D Geometry Scenario/Problem: You want to render 3D geometry. Solution: Starting in this section, you’ll see that WPF provides the unprecedented ability to merge 3D graphics with standard user interface elements and multimedia. Effectively using 3D graphics requires learning a little about cameras, lighting, materi- als, and coordinate systems. Thankfully, WPF makes a lot of this very easy. This simple demonstration creates a cube, complete with color and lighting, as seen in Figure 18.6 FIGURE 18.6 This cube demonstrates simple lighting and texture usage. From the Library of Skyla Walker ptg 390 CHAPTER 18 WPF First, the geometry needs to be defined. For our simple examples, the shapes will be defined in the Window.Resources sections. Here is the definition for the six faces of the cube: <Window.Resources> <MeshGeometry3D x:Key=”faceNear” Positions=”-1,-1,1 1,-1,1 1,1,1 -1,1,1” TriangleIndices=”0 1 2 0 2 3” TextureCoordinates=”0,1 1,1 1,0 0,0” Normals=”0,0,1 0,0,1 0,0,1 0,0,1”/> <MeshGeometry3D x:Key=”faceFar” Positions=”-1,-1,-1 1,-1,-1 1,1,-1 -1,1,-1” TriangleIndices=”0 1 2 0 2 3” /> <MeshGeometry3D x:Key=”faceLeft” Positions=”-1,-1,-1 -1,-1,1 -1,1,1 -1,1,-1” TriangleIndices=”0 1 2 0 2 3”/> <MeshGeometry3D x:Key=”faceRight” Positions=”1,-1,1 1,-1,-1 1,1,-1 1,1,1” TriangleIndices=”0 1 2 0 2 3”/> <MeshGeometry3D x:Key=”faceTop” Positions=”-1,1,1 1,1,1 1,1,-1 -1,1,-1” TriangleIndices=”0 1 2 0 2 3”/> <MeshGeometry3D x:Key=”faceBottom” Positions=”-1,-1,-1 1,-1,-1 1,-1,1 -1,-1,1” TriangleIndices=”0 1 2 0 2 3”/> <MaterialGroup x:Key=”defaultMaterial”> <DiffuseMaterial Brush=”Red” /> <SpecularMaterial SpecularPower=”30” Brush=”Yellow” /> </MaterialGroup> </Window.Resources> The actual placement of these mesh geometries is done inside a Viewport3D element: <Grid> <! 3-D elements need to go inside a Viewport3D > <Viewport3D x:Name=”Viewport”> <! Camera > <Viewport3D.Camera> <OrthographicCamera From the Library of Skyla Walker ptg 391 Render 3D Geometry Width=”5” Position=”4,4,10” LookDirection=”-0.4,-0.4,-1” UpDirection=”0,1,0” /> </Viewport3D.Camera> <ModelVisual3D> <ModelVisual3D.Content> <GeometryModel3D Geometry=”{StaticResource faceNear}” Material=”{StaticResource defaultMaterial}” /> </ModelVisual3D.Content> </ModelVisual3D> <ModelVisual3D> <ModelVisual3D.Content> <GeometryModel3D Geometry=”{StaticResource faceFar}” Material=”{StaticResource defaultMaterial}”/> </ModelVisual3D.Content> </ModelVisual3D> <ModelVisual3D> <ModelVisual3D.Content> <GeometryModel3D Geometry=”{StaticResource faceLeft}” Material=”{StaticResource defaultMaterial}”/> </ModelVisual3D.Content> </ModelVisual3D> <ModelVisual3D> <ModelVisual3D.Content> <GeometryModel3D Geometry=”{StaticResource faceRight}” Material=”{StaticResource defaultMaterial}”/> </ModelVisual3D.Content> </ModelVisual3D> <ModelVisual3D> <ModelVisual3D.Content> <GeometryModel3D Geometry=”{StaticResource faceTop}” Material=”{StaticResource defaultMaterial}”/> </ModelVisual3D.Content> </ModelVisual3D> <ModelVisual3D> <ModelVisual3D.Content> <GeometryModel3D Geometry=”{StaticResource faceBottom}” From the Library of Skyla Walker [...]... 1,1 1,0 0,0” Normals=”0,0,1 0,0,1 0,0,1 0,0,1” /> ... xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” xmlns:interactive3D=”clr-namespace:_3DTools;assembly=3DTools” Title=”Movie and Controls in 3D” Height=”480” Width=”640” Loaded=”Window_Loaded”> From the Library of Skyla Walker Put Video on a 3D Surface 393 WPF Button Note that there is no NumericUpDown control in WPF (see Figure 18. 9) FIGURE 18. 9 No NumericUpDown control in WPF (Yet, we hope.) From the Library of Skyla Walker CHAPTER 19 ASP.NET IN THIS CHAPTER View Debug and Trace Information Determine Web Browser Capabilities Redirect to Another Page Use Forms Authentication for User... From the Library of Skyla Walker 398 CHAPTER 18 WPF The code-behind provides the button functionality: public partial class Window1 : Window { public Window1() { InitializeComponent();... environment into something the elements can understand In this example, let’s add some file selection and playback controls to our crazy video player (see Figure 18. 7) You will also need to add a reference to the 3DTools.dll assembly in your project FIGURE 18. 7 A cube playing a slideshow video, with working controls I dare you to try this in Windows Forms Here is the complete code: . 0,0,1”/> <MeshGeometry3D x:Key=”faceFar” Positions= -1 ,-1 ,-1 1 ,-1 ,-1 1,1 ,-1 -1 ,1 ,-1 ” TriangleIndices=”0 1 2 0 2 3” /> <MeshGeometry3D x:Key=”faceLeft” Positions= -1 ,-1 ,-1 -1 ,-1 ,1 -1 ,1,1 -1 ,1 ,-1 ” TriangleIndices=”0 1 2 0. 3”/> <MeshGeometry3D x:Key=”faceRight” Positions=”1 ,-1 ,1 1 ,-1 ,-1 1,1 ,-1 1,1,1” TriangleIndices=”0 1 2 0 2 3”/> <MeshGeometry3D x:Key=”faceTop” Positions= -1 ,1,1 1,1,1 1,1 ,-1 -1 ,1 ,-1 ” TriangleIndices=”0 1 2 0. -1 ,1 ,-1 ” TriangleIndices=”0 1 2 0 2 3”/> <MeshGeometry3D x:Key=”faceBottom” Positions= -1 ,-1 ,-1 1 ,-1 ,-1 1 ,-1 ,1 -1 ,-1 ,1” TriangleIndices=”0 1 2 0 2 3”/> <MaterialGroup x:Key=”defaultMaterial”> <DiffuseMaterial

Ngày đăng: 12/08/2014, 09:23

TỪ KHÓA LIÊN QUAN