在Silverlight 2中構建可重用控件

在Silverlight 2中構建可重用控件

小序:

本文是Silverlight Lab系列的第二部分,詳細介紹瞭如何創建和使用Silverlight用戶控件。此係列的其它部分包括動畫,網絡,和瀏覽器集成等,英文Lab可以在Silverlight.net上免費獲取。由於第一次翻譯Silverlight 2的英文文章,錯誤在所難免,歡迎提出意見。翻譯文字本來是嵌入在英文中的,在發佈到博客時發現原文的格式比較複雜,簡單的拷貝和粘貼會導致格式十分混亂,只好一段一段的拷貝並格式化才完成了這篇翻譯,其中也發現了一些Word操縱的技巧,算是意外收穫。

老外的入門指南寫的非常精彩,既有詳細的步驟,即使一個初學者也可以按照順序一步一步完成,又有各種提示幫助你深入瞭解各種基本概念,如果我們的中文資料也能這樣那真是再好不過了。

 

Microsoft® Silverlight 

User Controls – MIX08

 

Building Reusable Controls in Silverlight 2

The most common way to build reusable components in Silverlight 2 is through user controls. A user control is a simple derivative of the System.Windows.Controls.Control base class (just like the TextBox control is, for example), and acts as a generic container of other controls. Much like its web counterpart in ASP.NET, you can use the designer to lay out controls and then add handlers, set properties, and invoke methods to interact with those controls from a code behind class. This package of user interface and behavior can then be dropped into any other XAML file in your project as an encapsulated control. Furthermore, you can add properties, methods, and events to your user control to allow customization on a per-instance basis.

You may have noticed that the default Silverlight project in Visual Studio 2008 creates a UserControl for you in the main Page.xaml class, and then loads this control as the root object on application startup. We will start with a more traditional way of creating user controls – declaratively, but will also explore techniques for dynamically adding controls later on.

This lab walks you through the steps of creating reusable controls in Silverlight 2.

 

This lab is not designed to be worked through from start to finish. It is structured as a series of practical ‘how to’ exercises, illustrating certain techniques. You are encouraged to explore and experiment.

 

Contents:

A.      Creating User Controls in Visual Studio 2008

B.      Editing a User Control with Expression Blend

C.       Adding properties to a User Control

D.      Exposing events from a User Control

E.       Dynamically adding User Controls

F.       Building User Controls in Independent Assemblies

A Creating User Controls in Visual Studio 2008

You can create User Controls in both Visual Studio 2008 and Blend 2.5 March 2008 Preview and use the same files within both programs.  In this section we will use Visual Studio to create a User Control.

你可以在 Visual Studio 2008 Blend 2.5 March 2008 Preview中創建用戶控件,並使用相同的文件。在此節中我們將使用Visual Studio創建用戶控件。

1.       In Visual Studio, create a new Silverlight project called UserControls. Let Visual Studio create an associated web project.
Visual Studio中,創建一個新的稱爲UserControlsSilverlight項目。讓Visual Studio創建一個關聯網站項目。

2.       We are going to create a simple button control that responds to mouse clicks and runs an animation that expands the button to indicate it was clicked. To add a new user control in Visual Studio, right click on your UserControls project within the Solution  Explorer and select Add | New Item… Select Silverlight from the list of Categories and choose the Silverlight Control template. Name the new control ExpandingButton.xaml.
我們將創建一個簡單的響應鼠標點擊的按鈕控件,並且在被點擊時運行一個伸縮動畫。爲了添加一個新的用戶控件,右鍵點擊位於解決方案瀏覽器中的UserControls項目,選擇Add|New Item…從類別列表中選擇Silverlight,並選擇Silverlight Control模板。

3.       Inspect the resulting files that were added to your project: ExpandingButton.xaml and ExpandingButton.xaml.cs. Note that the XAML file contains a UserControl declaration with single Grid element within it. Its Class attribute should be set to UserControls.ExpandingButton, which is the partial class defined in ExpandingButton.xaml.cs. Anything you add to either the XAML file or the .cs file will be added to the generated class definition (merged at compile time using the partial class mechanism in C#).
檢查剛纔添加到你的項目中的文件: ExpandingButton.xaml ExpandingButton.xaml.cs.注意XAML文件包含一個UserControl聲明,在它的裏面有一個Grid元素。它的Class特性應該被設置爲UserControls. ExpandingButtonExpandingButton類是一個部分類,它的定義位於文件 ExpandingButton.xaml.cs中。你添加到XAML文件或.cs文件中的任何東西都將被添加到動態生成的類定義中(在編譯時使用C#的部分類機制合併到一起)。

4.       In order to quickly test your new control, add a TextBlock element with some sample text in it as a child element to the Grid element in ExpandingButton.xaml.

<Grid x:Name="LayoutRoot" Background="White">

<TextBlock Text="Hello User Controls!" />

</Grid>
爲了快速測試你的新控件,添加一個TextBlock元素作爲 ExpandingButton.xaml文件中Grid元素的孩子,並在其中添加一些示例文本。

5.       To use your new control from within another page, you will need to add an XML namespace declaration that points to the CLR namespace in which the control is defined, as well as the assembly in which it resides. Open your Page.xaml file (the main XAML page for your project) and add the following namespace declaration just below the ‘x’ namespace declaration:
xmlns:uc="clr-namespace:UserControls"
By default, Visual Studio will have wrapped your control class in a namespace with the same name as the project, so unless you changed it the namespace should be UserControls.
要在另一個頁面中使用你的新控件,需要添加一個XML名字空間聲明,它指向定義那個控件的CLR名字空間,和控件所在的程序集。打開你的Page.xaml文件(你的項目的主XAML頁面)並在’x’名字空間聲明的下方添加下面的名字空間聲明。
xmlns:uc=”clr-namespace:UserControls”
默認情況下,Visual Studio將你的控件類包裹在與項目同名的名字空間中,因此除非你改變了它,否則名字空間會是UserControls

6.       With the namespace declaration in place, you are now ready to place an instance of your control on the page. In your Page.xaml file, add an instance of your control using the uc prefix declared in the last step inside of the root Grid element. (Note you may not get intellisense for your control until you compile the project once, which you may want to do at this point). Since we will be referring to this control programmatically later on, give it a name identifier of myButton as well.
一旦在合適的地方聲明瞭名字空間,那麼現在你就可以在頁面中添加你的控件了。在你的Page.xaml文件中,使用uc前綴添加一個你的控件的實例。(注意你可能需要編譯一次你的項目,才能對你的控件支持智能提示,現在你就可以編譯了)。由於我們想以後可以編程引用我們的控件,因此給它一個名字標識符

myButton

<Grid x:Name="LayoutRoot" Background="White">

<uc:ExpandingButton x:Name="myButton" />

</Grid>

7.       That should be it! Now try running your project (launch the test Web site with Debug | Start without debugging or Ctrl-F5). You should see your control text displayed in the browser.
大功告成了!現在試着運行你的項目(使用Debug|Start without debugging或者Ctrl+F5啓動test web site)。你應該能夠看到你的控件的文本顯示在瀏覽器中。

B. Editing a User Control with Expression Blend

One of the key advantages to working with Silverlight is the ability to edit the XAML interface independently of (and concurrently with) the program development, creating a two-way conversation between designer and developer. User controls are no exception to this rule, and in this section you will use Expression Blend 2.5 to design the look and feel of your button control, including an animation to be invoked whenever the button is clicked. You will then move back to Visual Studio to add the logic to trigger the animation.
使用Silverlight的一個重用優點是能夠在開發程序時獨立(並行)的編輯XAML界面,建立起設計者和開發者之間的雙向對話。用戶控件也不例外,在此節中我們將使用 Expression Blend 2.5設計你的按鈕控件的觀感,包括點擊按鈕時的動畫。然後你可以在Visual Studio中添加邏輯觸發動畫。

1.       Open Expression Blend 2.5 and choose Open Project… from the initial prompt. Locate the UserControls.sln file located within the UserControls directory you created for the last project.

Note: if you already have Visual Studio open, you can also right-click on a XAML file in the Solution Explorer and select “Open in Expression Blend…”.
打開 Expression Blend 2.5從起始彈出列表中選擇 Open Project…定位位於UserControls目錄中的 UserControls.sln文件。
注意:如果你已經打開了Visual Studio,那麼你也可以在解決方案瀏覽器中右擊一個XAML文件,選擇“Open in Expression Blend…”

2.       In the Project tab on the right, locate your ExpandingButton.xaml file and double click it to open. Use the Direct Selection tool (the white arrow cursor) to select the TextBlock you added earlier and delete it.
在右側的Project標籤中,定位你的 ExpandingButton.xaml文件,雙擊打開它。使用Direct Selection工具(白色箭頭光標)選擇你先前添加的TextBlock並刪除它。

3.       In the Objects and Timeline tab on the left, right-click LayoutRoot and select “Change LayoutType -> Canvas”. The will take advantage of absolute positioning within a Canvas to animate the interaction.
在左側的 Objects and Timeline中,右擊LayoutRoot選擇“Change LayoutType -> Canvas”。這樣可以利用Canvas的絕對定位特點來創建交互動畫。

4.       Using the Ellipse tool, draw an ellipse in the top left-hand corner of the canvas approximately 100x50 in dimension. Change the fill color of the ellipse to something more eye catching than plain white (the solution uses red, but feel free to draw on your designer capabilities to create a more sophisticated looking button here).
使用 Ellipse工具,在canvas左上角繪製一個大約100x50的橢圓。改變橢圓的fill顏色以吸引眼球(這裏使用紅色,但是可以自由發揮你的設計天賦來創建一個更加複雜的按鈕)。

5.       Next, use the TextBlock tool to add text to the button (be sure to use the TextBlock tool and not the TextBox tool for this). Set the text initially to “[default]” to indicate that is the default text for the button and can be changed. Center the TextBlock within the Ellipse you created for the button. The final design should look something like:
然後,使用TextBlock工具向按鈕添加文本(在這裏一定要使用TextBlock工具而不是TextBox工具)。最初將文本設置爲“[default]”表示按鈕的默認文本。將Ellipse中的TextBlock居中。最終的設計看起來就像這樣:



6.       We’re going to want to animate these two elements as one in our animation, so envelop them in their own Canvas by selecting both (with the Direct Selection tool and shift-clicking), then right-click on the selection and select Group Into | Canvas. Set the name of this new canvas to buttonCanvas.
在動畫中我們希望將這兩個元素作爲一個整體,可以將這兩個元素封裝在它們的Canvas中,只需選擇它們(使用Direct Selection shift-clicking),右擊並選擇 Group Into | Canvas.將這個新的canvas命名爲 buttonCanvas

7.       Next, change the size of the root UserControl element to more closely reflect the size we want the button to occupy. Double-click the UserControl element in your Objects and Timeline toolbar, and change the Width to 300 and the Height to 150.
然後改變 root UserControl元素的大小使它更接近我們所希望的大小。雙擊位於 Objects and Timeline工具欄中的 UserControl元素,將其高度改變爲150,寬度改變爲300

8.       The last task in Blend is to create an animation for the button to play when it is clicked. Add a new animation by clicking on the ‘+’ sign next to the storyboard control in the Objects and Timeline toolbar. Name the animation ‘ButtonClickAnimation’.
最後在Blend中創建一個點擊按鈕時的動畫。單擊 Objects and Timeline工具欄中靠近storyboard控件的’+’號添加一個新的動畫。將其命名爲‘ButtonClickAnimation’.

9.       You should now be in timeline recording mode. To make it easier to modify the animation and see what you are doing, you may want to change the window layout to the animation workspace (do this with the Window | Animation Workspace menu item).
Select the buttonCanvas and record a key frame at 0 seconds (press the Record Keyframe button with the green ‘+’ sign in the animation editor)


現在你應該處於 timeline recording模式。爲了便於修改動畫,你可以切換到animation工作區(單擊 Window | Animation Workspace菜單條目)。

10.   Next, move the timeline position to 0.5 seconds, and then Shift-drag the resize handle on the lower right of the Canvas you added earlier (that contains the Ellipse and TextBlock) until the button is about 300x150 in dimension. Then move the timeline position to 1.0 seconds and Shift-drag the same resize handle so the canvas is back to its original size of 100x50. Feel free to experiment with more interesting effects here, like using Ease In and Ease Out to smooth out the animation. You can test your animation by pressing the ‘play’ button above the timeline.
下一步,移動timeline位置到0.5秒, Shift-drag 先前添加的Canvas(包含EllipseTextBlock)右下角的resize句柄直到按鈕尺寸大約爲300x150。然後移動timeline位置到1秒並 Shift-drag同樣的resize句柄使它回到原來的尺寸100xx50。可以自由實驗一些更有趣的效果,例如使用 Ease In and Ease Out以平滑動畫。你可以單擊timeline上面的play按鈕測試你的動畫。

11.   Save ExpandingButton.xaml in Blend and go back to Visual Studio (if you left the ExpandingButton.xaml file open in Visual Studio as you used Blend, you should be prompted to reload the file as it was changed – say yes). Go ahead and run your test Web site again with the new XAML in place to verify that your control now renders as the button you designed in Blend.
Blend中保存ExpandingButton.xaml,返回Visual Studio(如果當你使用Blend時, ExpandingButton.xamlVisual Studio中是打開的,那麼你應該選擇reload文件因爲它被改變了)。繼續並運行你的測試Web網站確保你的控件現在和你在Blend中的設計一致。

12.   Now you will kick off the animation you defined in Blend in response to the button canvas being clicked. Open your ExpandingButton.xaml.cs file, and in the constructor, after the call to InitializeComponent() subscribe a delegate to the MouseLeftButtonUp event.
The simplest way to do this is to type this.MouseLeftButtonUp +=[tab][tab] and Visual Studio will generate a new function for you to handle the event. Implement the handler by calling Begin() on your ButtonClickAnimation.
現在你可以添加在Blend中定義的響應單擊的動畫了。打開 ExpandingButton.xaml.cs文件,在構造函數中,在 InitializeComponent()調用之後添加一個 MouseLeftButtonUp事件的委託。

public ExpandingButton()

{

// Required to initialize variables

InitializeComponent();

 

this.MouseLeftButtonUp +=
    new MouseButtonEventHandler(ExpandingButton_MouseLeftButtonUp);

}

 

void ExpandingButton_MouseLeftButtonUp(object sender,
                                      MouseButtonEventArgs e)

{

this.ButtonClickAnimation.Begin();

}



Note: you could also have added a handler for this event declaratively through the XAML, they are equivalent techniques.
注意:你也可以在XAML中聲明式的添加此事件的處理器,兩種方法的效果是一樣的。

13.   Try running your test web site and verify that your control now expands and contracts in response to being clicked – it now lives up to its name as an expanding button!
試着運行你的測試網站,確保單擊你的控件時會出現伸縮效果-現在它纔是名副其實的 expanding按鈕。

14.  One of the key benefits of encapsulating XAML and logic into a user control is that you can easily create multiple instances. Test this by changing the LayoutRoot Grid to a  4x4 Grid in Page.xaml and place a separate instance of your ExpandingButton control in each cell, as follows:
XAML和邏輯封裝進用戶控件的一個好處是你可以輕鬆的創建多個按鈕實例。將LayoutRoot Grid改變爲一個4x4 Grid,並在每一個單元格中放置一個單獨的 ExpandingButton按鈕,如下所示:
<Grid x:Name="LayoutRoot" Background="White">

<Grid.RowDefinitions>

<RowDefinition />

<RowDefinition />

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition />

<ColumnDefinition />

</Grid.ColumnDefinitions>

<uc:ExpandingButton Grid.Row="0" Grid.Column="0" x:Name="myButton1" />

<uc:ExpandingButton Grid.Row="0" Grid.Column="1" x:Name="myButton2" />

<uc:ExpandingButton Grid.Row="1" Grid.Column="0" x:Name="myButton3" />

<uc:ExpandingButton Grid.Row="1" Grid.Column="1" x:Name="myButton4" />  

</Grid>

Try running your test web site again, this time you should see four instances of your ExpandingButton control arranged in a grid!

C. Adding properties to a User Control

A control that offers no properties for customization will not likely be very reusable, since each instance will render the same way. Our button is a good example of a control that would benefit from exposing properties, which is what we will do now. In our case we will let the user change both the text and the color of the button to customize its appearance.

沒有提供自定義屬性的控件重用性不大,因爲每個實例都以相同的方式呈現。我們的按鈕就是一個很好的例子,它從暴露屬性中受益良多,這就是我們現在想達到的目標。在這個例子中,用戶可以修改按鈕的文本和顏色來自定義按鈕的外形。

1.       First, we need to make sure the XAML elements whose properties we are going to expose are named and accessible from our code behind class. Open your ExpandingButton.xaml file, and add names to both the ellipse and text elements within the button canvas (use identifiers of buttonEllipse and buttonText respectively).
首先我們需要確保希望暴露屬性的XAML元素可以被我們的code-behind類訪問。打開 ExpandingButton.xaml文件,爲按鈕canvas中的ellipsetext元素添加名字(分別使用標識符 buttonEllipse buttonText)。

  <Ellipse x:Name="buttonEllipse" ... />

  <TextBlock x:Name="buttonText" ... />

2.       Open your ExpandingButton.xaml.cs code behind file, and add a public property of type string named label. Implement the get method of this property to return the current value of the Text property associated with the buttonText TextBlock element, and the set method to set the same value.
打開 ExpandingButton.xaml.cs code-behind文件,添加一個string類型的公有屬性並命名爲label。實現這個屬性的get方法以返回與buttonText TextBlock元素關聯的Text屬性的當前值,set方法也設置這個值。


public string Label

{

  get { return buttonText.Text; }

  set { buttonText.Text = value; }

}

 

3.       Add another property, of type Color named Color to expose the interior color of the ellipse. Implement the get method of this property to return the current value of the Color property of the Fill brush (you’ll have to cast it to a SolidColorBrush first), and the set method to assigning a new SolidColorBrush initialized to the incoming color value to the Fill property of the ellipse.
添加另一個Color類型名字爲Color的屬性暴露橢圓內部顏色。實現這個屬性get方法返回Fill畫刷Color屬性的當前值(你必須首先將它強制轉換爲SolidColorBrush),set方法爲橢圓的Fill屬性分配一個新的SolidColorBrush

public Color Color

{

  get { return ((SolidColorBrush)buttonEllipse.Fill).Color; }

  set { buttonEllipse.Fill = new SolidColorBrush(value); }

}

4.       Go back to your Page.xaml file, and set the Label and Color properties of each of your controls to something besides their defaults, for example:
回到Page.xaml文件,爲每個控件設置一個與默認值不同的LabelColor屬性,例如:

<uc:ExpandingButton Color="Pink" Label="Push me!" ... />

  <uc:ExpandingButton Color="Orange" Label="No me!" ... />

  <uc:ExpandingButton Color="Purple" Label="Wait me!" ... />

  <uc:ExpandingButton Color="Yellow" Label="Hey me!" ... />

5.       Try running your test web site again, and verify that your buttons now display different colors and text.
再次試着運行你得測試網站,確認你的按鈕現在呈現爲不同的顏色和文本。

D. Exposing events from a User Control

Like native controls do, you will often want to expose events from your user control, which is easy to do using the native delegate/event mechanism in the CLR. Our button control will obviously need a Click event to let the user know when it has been clicked, so we will add that next.

和原生控件一樣,你經常想爲你的用戶控件暴露事件,通過CLR原生支持的委託/事件機制的支持,這變得非常簡單。我們的按鈕控件很明顯需要一個Click事件讓用戶知道已經點擊了它,因此下面我們着手實現Click事件。

1.       In Visual Studio, open your user control code behind file, ExpandingButton.xaml.cs.
Visual Studio中,打開你的用戶控件code-behind文件 ExpandingButton.xaml.cs

2.       Add a public event of type EventHandler to your ExpandingButton class named Click.
向你的 ExpandingButton類添加一個EventHandler類型的公有事件,命名爲Click

public event EventHandler Click;

3.       Invoke the event from within your MouseLeftButtonUp event handler, firing the event only if the Handled property of the incoming MouseButtonEventArgs is false and the Click delegate is not null. By setting the handled property of the incoming MouseButtonEventArgs to true, you are terminating the ‘bubbling’ of the event so it will not be passed up the chain to parent controls.

      void ExpandingButton_MouseLeftButtonUp(object sender,

                                              MouseButtonEventArgs e)

{

this.ButtonClickAnimation.Begin();

if (!e.Handled && (Click != null))

   Click(this, EventArgs.Empty);

 }

從你的 MouseLeftButtonUp事件處理器中觸發Click事件,並且僅當傳遞進來的 MouseButtonEventArgsHandled屬性爲falseClick委託不爲空時才觸發事件。通過設置傳遞進來的 MouseButtonEventArgshandled屬性爲true,可以終止事件的冒泡,這樣事件將不會傳遞到父控件中。

4.       To test your new event, open your Page.xaml file, and in one of your ExpandingButton control declarations, add a handler for the Click event type typing Click=[tab] which will generate a new handler in your code behind file named myButton1_Click.
爲了測試這個新事件,打開Page.xaml文件,在其中一個 ExpandingButton控件聲明中,添加一個Click事件的處理器,鍵入Click=[tab]會自動在你的code-behind文件中生成一個名字爲 myButton1_Click的處理器。

<uc:ExpandingButton Color="Pink" Label="Push me!" Grid.Row="0" Grid.Column="0" x:Name="myButton1" Click="myButton1_Click"/>

5.       Implement the handler to change the Label of the button to something different so you know it was clicked. You can use the incoming sender parameter to access the control that generated the event, first casting it to the ExpandingButton type.

       private void myButton1_Click(object sender, EventArgs e)

{

((ExpandingButton)sender).Label = "Again!";

}

在事件處理器中改變按鈕的Label,這樣你能知道它被單擊了。你可以使用傳遞進來的sender參數訪問產生事件的控件,當然首先要將它強制轉換爲 ExpandingButton類型。

6.       Try running your test web site, and verify that the button changes it label once it has been clicked.
試着運行你的test網站,並確認當單擊按鈕時,它被改變了。

7.       Feel free to wire up handlers to the Click events of each of the other button instances on the page as well.

E. Dynamically adding User Controls

You may need to add user controls dynamically to your pages, whether in response to user input or for programmatic control over the layout. Fortunately this is no more difficult than it is for standard controls, so in this part we will dynamically add an instance of our ExpandingButton control to a Canvas on our main page.

你可能需要動態添加用戶控件到你的頁面中,無論是爲了響應用戶輸入或者爲了編程控制佈局。幸運的是,這與添加標準控件一樣簡單,因此在本小節中,我們將動態添加一個 ExpandingButton控件實例到主頁面的一個Canvas中。

1.       To dynamically add a control to a page, you need to add it to the Children of a container, so in preparation for an instance of our control to the page, insert a new Canvas element into a new row of the Grid in your Page.xaml file. To do this, add another RowDefinition element to the RowDefinitions section of your Grid. Then add a Canvas inside the Grid with its Row number set to 2. Name the new canvas buttonContainerCanvas.
爲了動態向一個頁面添加控件,需要將控件添加到容器的孩子中,因此爲了添加此控件的實例到頁面中,爲你的Page.xaml文件Grid元素添加新的一行,以插入一個新的Canvas元素。向Grid元素的RowDefinitions節添加另一個RowDefinition元素。然後在Grid中添加一個Row屬性爲2Canvas。將這個新Canvas命名爲 buttonContainerCanvas

<Grid>

    <Grid.RowDefinitions>

        <RowDefinition />

        <RowDefinition />

        <RowDefinition />

    </Grid.RowDefinitions>

    ...

    <Canvas x:Name="buttonContainerCanvas" Grid.Row="2" />

</Grid>

2.       To dynamically inject a new instance of your control, open the Page.xaml.cs file, in the constructor after the call to InitializeComponent(), create a new instance of your ExpandingButton class.
爲了動態插入一個控件的實例,打開 Page.xaml.cs文件,在構造函數中 InitializeComponent()調用之後,創建一個ExpandingButton類實例。

ExpandingButton dynamicButton = new ExpandingButton();

3.       Set the Label and Color properties as desired, plus feel free to wire up the Click event to your existing handler that changes the Label text.
設置LabelColor屬性,綁定Click事件到改變Label文本的處理器。

dynamicButton.Label = "Dynamic button";

dynamicButton.Color = Colors.Red;

dynamicButton.Click += myButton1_Click;

4.       Finally, add the newly created button to the Children collection of the buttonContainerCanvas you added earlier.
最後,向你先前添加的 buttonContainerCanvasChildren集合中添加新創建的按鈕。

buttonContainerCanvas.Children.Add(dynamicButton);

5.       Try running your test web site, and verify that the new ‘dynamic’ button shows up in the last row of the grid.
試着運行你的測試web網站,並確認新動態按鈕出現在grid的最後一行。

F. Building User Controls in Independent Assemblies

If you need to use your user control in multiple projects (for example, a common menu control that you would like to share across applications), you don’t want to copy the control’s XAML and source code since you would end up maintaining separate implementations. Instead, it is preferable to isolate the control into its own assembly and share only the resulting compiled binary across projects. This is easily accomplished with Visual Studio 2008 as well by creating a separate Silverlight Class Library project to house your User Control. In this part, you will create a new user control housed in a separate assembly, and then reference that control from your original project.

如果你需要在多個項目中使用你的用戶控件(例如,你需要在多個應用程序中使用菜單控件),但是你不想拷貝控件的XAML和源代碼,因爲那樣你將不得不維護多個實現。相反,將控件隔離到單獨程序集,在多個項目中只共享最終的編譯後的二進制文件更爲穩妥。在Visual Studio 2008中這也很容易辦到,通過創建一個單獨的Silverlight類庫項目來承載你的用戶控件即可。在本部分中,你將創建一個新的封裝在獨立程序集中的用戶控件,並且在原來的項目中引用這個控件。

1.       In your UserControls solution in Visual Studio, add a new Silverlight Class Library project by right-clicking on the solution icon in the solution explorer and selecting Add | New Project… . Choose Visual C# | Silverlight as the project type, and select the Silverlight Class Library template. Name the project ExternalUserControl and hit OK.
UserControls解決方案中,右擊解決方案瀏覽器中的解決方案圖標選擇 Add | New Project…添加一個新的Silverlight Class Library項目。選擇 Visual C# | Silverlight作爲項目類型,選擇 Silverlight Class Library模板。命名爲 ExternalUserControl,然後單擊OK

2.       This will create a new class library project compiled with the Silverlight assemblies, which you can then deploy as part of another Silverlight project. To begin, delete the default Class1.cs file that was added by the project wizard – we’re not going to need it.
這將創建一個新的類庫項目並與Silverlight程序集一起編譯,你可以將它作爲另一個Silverlight項目的一部分一起部署。讓我們開始吧,刪除默認的Class1.cs文件,它是由項目嚮導添加的-我們不需要它。

3.       Next, add a new Silverlight User Control by right clicking on your ExternalUserControl project within the Solution  Explorer and selecting Add | New Item… . Select Silverlight from the list of Categories and choose the Silverlight Control template. Name the new control AnotherControl.xaml.
然後,右擊解決方案瀏覽器中的 ExternalUserControl項目選擇 Add | New Item…來添加一個新的Silverlight用戶控件。從Categories中選擇Silverlight,選擇Silverlight控件模板。命名新控件爲AnotherControl.xaml

4.    Open the AnotherControl.xaml file, and add a simple TextBlock element with some text so we can see the control render something when we deploy it.
打開 AnotherControl.xaml文件,添加一個簡單的 TextBlock元素和一些文本,這樣當我們部署時,可以直到控件呈現出來。
<
Grid x:Name="LayoutRoot" >

    <TextBlock Text="Hi from another assembly!" />

</Grid>

5.       Building a control in a separate assembly is no different from building it within a project, so we will leave our control to render just this simple text, understanding that all of the techniques outlined earlier in this lab could be applied here.
在一個單獨的程序集中構建一個控件與在一個項目中構建它並沒有什麼不同,因此在這裏我們只是呈現一些簡單的文本,重要的是理解先前使用的技術在這裏也是適用的。

6.       Compile your new control, and then add a reference to it in your UserControls project. To add a reference, right-click on the References icon under your UserControls project in the Solution Explorer, and select Add Reference… . In the Add Reference dialog, click on the Projects tab, and select the ExternalUserControl project and hit OK.

7.       編譯你的新控件,然後添加一個到UserControls項目的引用。爲了添加一個引用,在解決方案瀏覽器中UserControls項目標籤上右擊Reference圖標,點擊Project標籤,選擇ExternalUserControl項目並單擊OK


To verify that your external control can now be used, open your Page.xaml file and add a new namespace declaration to the UserControl element pointing to the namespace and assembly of your external control.
爲了確認現在可以使用你的外部控件,打開你的Page.xaml文件,添加一個到UserControl元素的名字空間聲明,其中名字空間和程序集指向你的外部控件。

xmlns:euc="clr-namespace:ExternalUserControl;assembly=ExternalUserControl"

8.       Now add an instance of AnotherControl to your page using the euc namespace. The solution places this control in the third row and second column of the existing Grid, which was not in use.
現在使用euc名字空間添加一個 AnotherControl實例到你的頁面中。這裏將控件放到Grid的第三行第二列中。

<euc:AnotherControl x:Name="myOtherControl" Grid.Row="2" Grid.Column="1" />

9.       Try running your test web site again, and verify that the TextBlock of your external control renders correctly. You could use this technique to create controls to share and distribute easily across projects and applications.
再次試着運行你的測試web網站,確保外部控件的TextBlock呈現正確。你可以使用此技術創建控件,並在不同的項目和應用程序中輕鬆的共享和發佈它們。

 

發佈了46 篇原創文章 · 獲贊 1 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章