如何在silverlight 4中创建指向文件后面的单个代码的多用户控件控件、多用户、后面、代码

2023-09-07 14:51:31 作者:哥、淫領風騷

我正在创建一个应用程序,其中我有 2 个用户控件,是否有可能,我们有 2 个 xaml 用户控制页面并且在 xaml.cs 文件后面有 1 个代码?

I am creating a application, in which i have 2 user control, is it possible that, we have 2 xaml user control page and having 1 code behind xaml.cs file?

推荐答案

首先创建三个文件,首先将代码隐藏".cs 文件创建为一个简单的类:-

Start off by creating three files, first the "code-behind" .cs file is created as a simple class:-

 public class MyCommonUserControl : UserControl
 {

 }

注意它没有 InitializeComponent 调用.

现在创建一个新的 UserControl 然后修改它的 xaml 看起来像这样:-

Now create a new UserControl then modify its xaml to look like this:-

<local:MyCommonUserControl x:Class="YourApp.FirstMyCommonUserControl "
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:YourApp"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

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

    </Grid>

</local:MyCommonUserControl >

注意添加 xmlns:local 别名以指向您应用的命名空间,然后将 UserControl 标记更改为我们真正想要的基本控件.

Note the addition the xmlns:local alias to point to your app's namespace then the change of the UserControl tag to the base control we actually want.

您可以将 .xaml.cs 修改为:-

You would modify the .xaml.cs to this:-

public partial class FirstMyCommonUserControl : MyCommonUserControl 
{
    public FirstMyCommonUserControl()
    {
        InitializeComponent();
    }
}

这就是 .xaml.cs 需要包含的全部内容.

That is all the .xaml.cs needs to contain.

然后您可以对 SecondMyCommonUserControl 重复此操作,依此类推.将所有通用代码放在 MyCommonUserControl 基类中.

You can then repeat this for SecondMyCommonUserControl and so on. Place all the common code in the base MyCommonUserControl class.

遗憾的是,MS 一开始并没有预料到这一点,在底层 UserControl 中添加了一个空的虚拟 InitializeComponent 方法,并让 .gics 自动生成代码 override 该方法意味着在这些情况下我们可以省去这个多余的 .xaml.cs 文件.

Its a pity MS didn't anticipate this in the first place, adding an empty virtual InitializeComponent method to the underlying UserControl and having the .g.i.cs auto-generated code override the method would have meant that we could dispense with this superflous .xaml.cs file in these cases.

 
精彩推荐
图片推荐