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

前端 未结 1 1512
心在旅途
心在旅途 2020-12-10 22:06

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条回答
  • 2020-12-10 22:31

    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.

    0 讨论(0)
提交回复
热议问题