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.