how to create Multiple user control that pointing single code behind file in silverlight 4

北战南征 提交于 2019-12-17 19:55:00

问题


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?


回答1:


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

 public class MyCommonUserControl : UserControl
 {

 }

Note it has no InitializeComponent call.

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 >

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.

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

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

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

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

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.



来源:https://stackoverflow.com/questions/6516211/how-to-create-multiple-user-control-that-pointing-single-code-behind-file-in-sil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!