I have already looked to similar answers and I don’t know why I am still have this error:
Severity Code Description Project File Line Suppression State
Error CS0263 Partial declarations of 'MainPage' must not specify different base classes MyNavDraw.Android (my path ...)MainPage.xaml.cs 13 Active
MainPage.xaml.cs:
namespace MyNavDraw
{
public partial class MainPage : MasterDetailPage
{
...
MainPage.xaml
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyNavDraw"
x:Class="MyNavDraw.MasterDetailPage">
<MasterDetailPage.Master>
...
What I tried so far:
In xaml I have replaced the tag to:
<we:MainPage ...
I checked «x:Class» and I think is correct the syntax, I have restarted the VS and I built again the solution.
I use Xamarin with VS 2017.
After a day (from this post question) I tried to put in comments the code of «MainPage.xaml» file. Then I saved it, I removed comments, saved it again and built the solution. I have a new error in built:
No way to resolve conflict between "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" and "mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e". Choosing "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" arbitrarily.
I have an other problem when I debug the app to my physical phone (android).
In My.Nav.Draw.Droid.MainPage.xaml.g.cs I have an exception Unhandled error.
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(MainPage));
What can be wrong?
C# Compiler Error
CS0263 – Partial declarations of ‘type’ must not specify different base classes
Reason for the Error
You’ll get this error in your C# code when you have defined the partial type with same name and each one of them has a different base class.
For example, lets try to compile the below code snippet.
using System;
namespace DeveloperPubNamespace
{
public class BaseClass1
{
public string Name { get; set; }
}
public class BaseClass2
{
public string Name { get; set; }
}
public partial class class1 : BaseClass2
{
}
public partial class class1 : BaseClass1
{
}
class Program
{
public static void Main()
{
Console.WriteLine("Welcome");
}
}
}
You’ll receive the error code CS0263 when you try to build the above C# program because you have declared multiple partial types “class1” but each one inheriting from a different base class “BaseClass1” and “BaseClass2”
Error CS0263 Partial declarations of ‘class1’ must not specify different base classes DeveloperPublish C:UsersSenthilsourcereposConsoleApp3ConsoleApp3Program.cs 15 Active

Solution
When you define a type in partial declarations in your C# program, it is important to specify the same base types for each of the partial types.
You can fix the above program by specifying the same base class for both the partial type declarations as shown below.
using System;
namespace DeveloperPubNamespace
{
public class BaseClass1
{
public string Name { get; set; }
}
public class BaseClass2
{
public string Name { get; set; }
}
public partial class class1 : BaseClass1
{
}
public partial class class1 : BaseClass1
{
}
class Program
{
public static void Main()
{
Console.WriteLine("Welcome");
}
}
}
почему у меня есть это сообщение об ошибке для UserControl:
частичное объявление
MyNamespace.MyUserControl не должен
указывать различные базовые классы
просто потому, что я унаследовал от другого класса UserControl, который я создал в другом пространстве имен, тогда как это другое пространство имен упоминается в XAML как
xmlns:my="clr-namespace:ReferedNamespace;assembly=ReferedNamespace"
3 ответов
здесь немного, но это обычно происходит, когда код позади и файл xaml не наследуются от одного и того же базового класса.
Так как у нас нет всех деталей, касающихся вашей проблемы,
Я создам ситуацию, которая вызовет такое же исключение,
это может помочь вам понять вашу проблему.
в качестве примера просто создайте новое приложение WPF с помощью Visual Studio,
XAML может выглядеть примерно так:
<Window x:Class="WpfApplication1.MainWindow" .....>
код сзади бы тогда содержалось что-то вроде этого:
public partial class MainWindow : Window
{
//Code here
}
обратите внимание на «частичный» модификатор здесь. Это означает, что этот класс (MainWindow) может
не определяется в одном файле, а распределяется по нескольким файлам,
в этом случае XAML (.код XAML.cs) и CS (.ТП) файлы.
Теперь добавьте новый UserControl в решение. Он будет называться UserControl1.
не внося никаких изменений в XAML, измените код для главного окна:
public partial class MainWindow : UserControl1
{
//Code here
}
Теперь вы получите исключение, о котором вы спрашивали.
ищите что-то подобное в своем коде, если вы все еще не можете найти решение,
пожалуйста, предоставьте больше кода.
смотреть на обоих .cs и .файлы XAML в этой части
-
in .файл xaml:
<Window x:Class="BUSsAsDesign.GUI.IGPopUP" > ...... </Window> -
in .cs файл:
namespace BUSsAsDesign.GUI { public partial class IGPopUP : Window { //code here } } -
теперь, если вы хотите изменить окно на UserControl
-
изменить
<Window x:Class="BUSsAsDesign.GUI.IGPopUP" > ....... </Window> <!--**becomes**--> <UserControl x:Class="BUSsAsDesign.GUI.IGPopUP" > ....... </UserControl>
namespace BUSsAsDesign.GUI
{
public partial class IGPopUP : Window
{
//code here
}
}
//**becomes**
namespace BUSsAsDesign.GUI
{
public partial class IGPopUP : UserControl
{
//code here
}
}
— надеюсь, это полезно :).
16
автор: شريف محمد شلبى البشبيشى
Я хотел добавить эту информацию. В Visual Studio 2017 есть ошибка, в которую я не успел углубиться, но она вызывает эту ошибку. (из ОП)
описание: при объявлении частичного класса как X: Class для файла XAML ресурса, это вызовет эту ошибку, и после удаления объявления, ошибка будет сохраняться.
чтобы воспроизвести эту ошибку (или если вы находитесь здесь, потому что вы получаете эту ошибку сообщение)
Шаг 1: создайте новый проект WPF.
Шаг 2: создать новый файл ресурсов
Шаг 3: измените пространство имен файлов ресурсов на основное пространство имен проектов (удалите бит в конце.)
Шаг 4: в разделе объявление/заголовок файлов ресурсов добавьте объявление x: Class, указывающее ваше MainWindow (объект окна запуска по умолчанию) в качестве класса для этого файла ресурсов. (НАПР: x: Class=MainWindow)
Шаг 5: Очистить/Перестроить Решение
Шаг 6: теперь вы должны получить эту ошибку от OP. Поэтому удалите объявление x: Class из своего заголовка в файле ресурсов и сохраните/очистите/перестройте проект.
Если ошибка была воспроизведена, ошибка должна остаться, даже если вы удалили объявление x:Class из файла ресурсов.
единственное решение, которое я мог найти для этой ошибки, это удалить проекты Bin и любая другая папка со сборками в ней.
после их удаления очистите / перестройте свой проект, и ошибка должна исчезнуть.
I repeatedly get this Error Message:Partial Declaration must not specify different Base Classes. Can somebody tell me what may be the cause of this. Here’s my code.
CashAdvancePage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ebmsMobile.CashAdvancePage"
Title="Cash Advance"
BackgroundImage="bg3.jpg">
<Label Text="This is the Cash Advance Page." VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>
CashAdvancePage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace ebmsMobile
{
public partial class CashAdvancePage : ViewCell
{
public CashAdvancePage()
{
//InitializeComponent();
//NavigationPage.SetHasNavigationBar(this, false);
var image = new Image
{
HorizontalOptions = LayoutOptions.Start
};
image.SetBinding(Image.SourceProperty, new Binding("ImageUri"));
image.WidthRequest = image.HeightRequest = 40;
var nameLayout = CreateNameLayout();
var viewLayout = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
Children = { image, nameLayout }
};
View = viewLayout;
}
static StackLayout CreateNameLayout()
{
var nameLabel = new Label
{
HorizontalOptions= LayoutOptions.FillAndExpand
};
nameLabel.SetBinding(Label.TextProperty, "DisplayName");
var twitterLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
Font = Fonts.Twitter
};
twitterLabel.SetBinding(Label.TextProperty, "Twitter");
var nameLayout = new StackLayout()
{
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Vertical,
Children = { nameLabel, twitterLabel }
};
return nameLayout;
}
}
}
asked May 12, 2016 at 4:15
10
As a late entry…
In case you were trying to create a base class for your pages…but it failed. You CAN inherit from a your own custom base class.
Here’s how…
1: CREATE A BASE CLASS PAGE (w/ a Code Behind Class):
For example, here is mine, but yours could be different…
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Pulse.Mobile.Views.BaseContentPage">
</ContentPage>
public partial class BaseContentPage : ContentPage
{
#region <Fields & Constants>
protected Style ValidationEntryErrorStyle = Application.Current.Resources["ValidationEntryErrorStyle"] as Style;
protected Style FormEntryStyle = Application.Current.Resources["FormEntryStyle"] as Style;
#endregion
#region <Constructors>
public BaseContentPage()
{
InitializeComponent();
}
#endregion
#region <Events>
protected override void OnAppearing()
{
base.OnAppearing();
LogHelper.Trace($"Screen - {this}", "Browsed");
}
#endregion
#region <Methods>
protected bool ValidateKeyPress(Entry entry, TextChangedEventArgs e, string regularExpression)
{
var text = e.NewTextValue;
// Allow Empty
if(string.IsNullOrWhiteSpace(text))
return true;
var result = Regex.IsMatch(e.NewTextValue, regularExpression);
return result;
}
protected void ValidateStyle(Entry control, bool isValid)
{
switch (isValid)
{
case false:
control.Style = ValidationEntryErrorStyle;
break;
default:
control.Style = FormEntryStyle;
break;
}
}
protected void ValidateStyle(Picker control, bool isValid)
{
switch (isValid)
{
case false:
control.Style = ValidationEntryErrorStyle;
break;
default:
control.Style = null;
break;
}
}
#endregion
}
2: REFERENCE THE BASE CLASS PAGE in your PAGE:
Make sure you reference your views in «xmlns:views». Take special care to notice the pages root element: «<views:BaseContentPage «
<?xml version="1.0" encoding="utf-8" ?>
<views:BaseContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:Pulse.Mobile.Views;assembly=Pulse.Mobile"
x:Class="Pulse.Mobile.Views.ShakeoutDocumentPage">
<ContentPage.Content>
// YOUR AWESOME CONTENT GOES HERE...
</ContentPage.Content>
</views:BaseContentPage>
answered Apr 5, 2019 at 19:42
Prisoner ZEROPrisoner ZERO
13.7k20 gold badges91 silver badges134 bronze badges
You need to inherit from ContentPage in the .cs when you use it as Rootelement in the XAML file.
The other problem is, that you need to assign your «viewLayout» to Content instead of View.
using Xamarin.Forms;
namespace ebmsMobile
{
public partial class CashAdvancePage : ContentPage // derive from ContentPage
{
public CashAdvancePage()
{
//InitializeComponent();
//NavigationPage.SetHasNavigationBar(this, false);
var image = new Image
{
HorizontalOptions = LayoutOptions.Start
};
image.SetBinding(Image.SourceProperty, new Binding("ImageUri"));
image.WidthRequest = image.HeightRequest = 40;
var nameLayout = CreateNameLayout();
var viewLayout = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
Children = { image, nameLayout }
};
Content = viewLayout; // <-- Set the ViewLayout as Content
}
static StackLayout CreateNameLayout()
{
var nameLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand
};
nameLabel.SetBinding(Label.TextProperty, "DisplayName");
var twitterLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
// Font = Fonts.Twitter
};
twitterLabel.SetBinding(Label.TextProperty, "Twitter");
var nameLayout = new StackLayout()
{
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Vertical,
Children = { nameLabel, twitterLabel }
};
return nameLayout;
}
}
}
answered May 12, 2016 at 6:46
2
You are mixing up two distinct things here: a page and a view cell.
It is possible for both pages and view cells to be created both through code and using XAML, but they are separate things.
When creating any component in XAML, be it page or view, the root node type must be the type that you are subclassing.
The code behind .cs file then has to derive from that same base class, or you can actually leave out the base class completely in the codebehind, as partial classes do not have to re-state what class they are deriving from.
So, for your CashAdvance page definition, definitely remove the «: ViewCell» part from the class definition in the codebehind.
Then you should probably build out your Page in XAML (otherwise, what is the point of using a xaml page anyway, if you build it out in code?)
If you actually need a custom viewcell (for eg. for use inside a ListView) then create another .xaml file for your viewcell, and build out it’s own ui there.
You can then reference it inside the page XAML or from codebehind.
For more details on using XAML, please take a look at the Xamarin XAML documentation
answered May 12, 2016 at 6:44
![]()
irrealirreal
2,18818 silver badges22 bronze badges
1
As a general idea, keep the xaml main tag matching the inheritance in .cs file to prevent different base classes error
so if :
<contentPage xmlns="http://xamarin......> </contentPage >
then .cs file normally will be
public partial class myPage : contentPage { ........}
answered Mar 22, 2019 at 9:05
I repeatedly get this Error Message:Partial Declaration must not specify different Base Classes. Can somebody tell me what may be the cause of this. Here’s my code.
CashAdvancePage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ebmsMobile.CashAdvancePage"
Title="Cash Advance"
BackgroundImage="bg3.jpg">
<Label Text="This is the Cash Advance Page." VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>
CashAdvancePage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace ebmsMobile
{
public partial class CashAdvancePage : ViewCell
{
public CashAdvancePage()
{
//InitializeComponent();
//NavigationPage.SetHasNavigationBar(this, false);
var image = new Image
{
HorizontalOptions = LayoutOptions.Start
};
image.SetBinding(Image.SourceProperty, new Binding("ImageUri"));
image.WidthRequest = image.HeightRequest = 40;
var nameLayout = CreateNameLayout();
var viewLayout = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
Children = { image, nameLayout }
};
View = viewLayout;
}
static StackLayout CreateNameLayout()
{
var nameLabel = new Label
{
HorizontalOptions= LayoutOptions.FillAndExpand
};
nameLabel.SetBinding(Label.TextProperty, "DisplayName");
var twitterLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
Font = Fonts.Twitter
};
twitterLabel.SetBinding(Label.TextProperty, "Twitter");
var nameLayout = new StackLayout()
{
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Vertical,
Children = { nameLabel, twitterLabel }
};
return nameLayout;
}
}
}
asked May 12, 2016 at 4:15
10
As a late entry…
In case you were trying to create a base class for your pages…but it failed. You CAN inherit from a your own custom base class.
Here’s how…
1: CREATE A BASE CLASS PAGE (w/ a Code Behind Class):
For example, here is mine, but yours could be different…
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Pulse.Mobile.Views.BaseContentPage">
</ContentPage>
public partial class BaseContentPage : ContentPage
{
#region <Fields & Constants>
protected Style ValidationEntryErrorStyle = Application.Current.Resources["ValidationEntryErrorStyle"] as Style;
protected Style FormEntryStyle = Application.Current.Resources["FormEntryStyle"] as Style;
#endregion
#region <Constructors>
public BaseContentPage()
{
InitializeComponent();
}
#endregion
#region <Events>
protected override void OnAppearing()
{
base.OnAppearing();
LogHelper.Trace($"Screen - {this}", "Browsed");
}
#endregion
#region <Methods>
protected bool ValidateKeyPress(Entry entry, TextChangedEventArgs e, string regularExpression)
{
var text = e.NewTextValue;
// Allow Empty
if(string.IsNullOrWhiteSpace(text))
return true;
var result = Regex.IsMatch(e.NewTextValue, regularExpression);
return result;
}
protected void ValidateStyle(Entry control, bool isValid)
{
switch (isValid)
{
case false:
control.Style = ValidationEntryErrorStyle;
break;
default:
control.Style = FormEntryStyle;
break;
}
}
protected void ValidateStyle(Picker control, bool isValid)
{
switch (isValid)
{
case false:
control.Style = ValidationEntryErrorStyle;
break;
default:
control.Style = null;
break;
}
}
#endregion
}
2: REFERENCE THE BASE CLASS PAGE in your PAGE:
Make sure you reference your views in «xmlns:views». Take special care to notice the pages root element: «<views:BaseContentPage «
<?xml version="1.0" encoding="utf-8" ?>
<views:BaseContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:Pulse.Mobile.Views;assembly=Pulse.Mobile"
x:Class="Pulse.Mobile.Views.ShakeoutDocumentPage">
<ContentPage.Content>
// YOUR AWESOME CONTENT GOES HERE...
</ContentPage.Content>
</views:BaseContentPage>
answered Apr 5, 2019 at 19:42
Prisoner ZEROPrisoner ZERO
13.7k20 gold badges91 silver badges134 bronze badges
You need to inherit from ContentPage in the .cs when you use it as Rootelement in the XAML file.
The other problem is, that you need to assign your «viewLayout» to Content instead of View.
using Xamarin.Forms;
namespace ebmsMobile
{
public partial class CashAdvancePage : ContentPage // derive from ContentPage
{
public CashAdvancePage()
{
//InitializeComponent();
//NavigationPage.SetHasNavigationBar(this, false);
var image = new Image
{
HorizontalOptions = LayoutOptions.Start
};
image.SetBinding(Image.SourceProperty, new Binding("ImageUri"));
image.WidthRequest = image.HeightRequest = 40;
var nameLayout = CreateNameLayout();
var viewLayout = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
Children = { image, nameLayout }
};
Content = viewLayout; // <-- Set the ViewLayout as Content
}
static StackLayout CreateNameLayout()
{
var nameLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand
};
nameLabel.SetBinding(Label.TextProperty, "DisplayName");
var twitterLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
// Font = Fonts.Twitter
};
twitterLabel.SetBinding(Label.TextProperty, "Twitter");
var nameLayout = new StackLayout()
{
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Vertical,
Children = { nameLabel, twitterLabel }
};
return nameLayout;
}
}
}
answered May 12, 2016 at 6:46
2
You are mixing up two distinct things here: a page and a view cell.
It is possible for both pages and view cells to be created both through code and using XAML, but they are separate things.
When creating any component in XAML, be it page or view, the root node type must be the type that you are subclassing.
The code behind .cs file then has to derive from that same base class, or you can actually leave out the base class completely in the codebehind, as partial classes do not have to re-state what class they are deriving from.
So, for your CashAdvance page definition, definitely remove the «: ViewCell» part from the class definition in the codebehind.
Then you should probably build out your Page in XAML (otherwise, what is the point of using a xaml page anyway, if you build it out in code?)
If you actually need a custom viewcell (for eg. for use inside a ListView) then create another .xaml file for your viewcell, and build out it’s own ui there.
You can then reference it inside the page XAML or from codebehind.
For more details on using XAML, please take a look at the Xamarin XAML documentation
answered May 12, 2016 at 6:44
![]()
irrealirreal
2,18818 silver badges22 bronze badges
1
As a general idea, keep the xaml main tag matching the inheritance in .cs file to prevent different base classes error
so if :
<contentPage xmlns="http://xamarin......> </contentPage >
then .cs file normally will be
public partial class myPage : contentPage { ........}
answered Mar 22, 2019 at 9:05
Я постоянно получаю это сообщение об ошибке: частичное объявление не должно указывать разные базовые классы. Может кто подскажет, в чем может быть причина этого. Вот мой код.
CashAdvancePage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ebmsMobile.CashAdvancePage"
Title="Cash Advance"
BackgroundImage="bg3.jpg">
<Label Text="This is the Cash Advance Page." VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>
CashAdvancePage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace ebmsMobile
{
public partial class CashAdvancePage : ViewCell
{
public CashAdvancePage()
{
//InitializeComponent();
//NavigationPage.SetHasNavigationBar(this, false);
var image = new Image
{
HorizontalOptions = LayoutOptions.Start
};
image.SetBinding(Image.SourceProperty, new Binding("ImageUri"));
image.WidthRequest = image.HeightRequest = 40;
var nameLayout = CreateNameLayout();
var viewLayout = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
Children = { image, nameLayout }
};
View = viewLayout;
}
static StackLayout CreateNameLayout()
{
var nameLabel = new Label
{
HorizontalOptions= LayoutOptions.FillAndExpand
};
nameLabel.SetBinding(Label.TextProperty, "DisplayName");
var twitterLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
Font = Fonts.Twitter
};
twitterLabel.SetBinding(Label.TextProperty, "Twitter");
var nameLayout = new StackLayout()
{
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Vertical,
Children = { nameLabel, twitterLabel }
};
return nameLayout;
}
}
}
4 ответа
Лучший ответ
Вам необходимо наследовать ContentPage в .cs, когда вы используете его в качестве Rootelement в файле XAML.
Другая проблема заключается в том, что вам нужно присвоить свой «viewLayout» Content вместо View.
using Xamarin.Forms;
namespace ebmsMobile
{
public partial class CashAdvancePage : ContentPage // derive from ContentPage
{
public CashAdvancePage()
{
//InitializeComponent();
//NavigationPage.SetHasNavigationBar(this, false);
var image = new Image
{
HorizontalOptions = LayoutOptions.Start
};
image.SetBinding(Image.SourceProperty, new Binding("ImageUri"));
image.WidthRequest = image.HeightRequest = 40;
var nameLayout = CreateNameLayout();
var viewLayout = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
Children = { image, nameLayout }
};
Content = viewLayout; // <-- Set the ViewLayout as Content
}
static StackLayout CreateNameLayout()
{
var nameLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand
};
nameLabel.SetBinding(Label.TextProperty, "DisplayName");
var twitterLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
// Font = Fonts.Twitter
};
twitterLabel.SetBinding(Label.TextProperty, "Twitter");
var nameLayout = new StackLayout()
{
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Vertical,
Children = { nameLabel, twitterLabel }
};
return nameLayout;
}
}
}
3
Marius Junak
12 Май 2016 в 06:46
Как поздний вход …
Если вы пытались создать базовый класс для своих страниц … но это не удалось. Вы МОЖЕТЕ наследовать от другого базового класса.
Вот как…
1: СОЗДАЙТЕ СТРАНИЦУ БАЗОВОГО КЛАССА (с классом скрытого кода) :
Например, вот мой, а ваш мог быть другим …
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Pulse.Mobile.Views.BaseContentPage">
</ContentPage>
public partial class BaseContentPage : ContentPage
{
#region <Fields & Constants>
protected Style ValidationEntryErrorStyle = Application.Current.Resources["ValidationEntryErrorStyle"] as Style;
protected Style FormEntryStyle = Application.Current.Resources["FormEntryStyle"] as Style;
#endregion
#region <Constructors>
public BaseContentPage()
{
InitializeComponent();
}
#endregion
#region <Events>
protected override void OnAppearing()
{
base.OnAppearing();
LogHelper.Trace($"Screen - {this}", "Browsed");
}
#endregion
#region <Methods>
protected bool ValidateKeyPress(Entry entry, TextChangedEventArgs e, string regularExpression)
{
var text = e.NewTextValue;
// Allow Empty
if(string.IsNullOrWhiteSpace(text))
return true;
var result = Regex.IsMatch(e.NewTextValue, regularExpression);
return result;
}
protected void ValidateStyle(Entry control, bool isValid)
{
switch (isValid)
{
case false:
control.Style = ValidationEntryErrorStyle;
break;
default:
control.Style = FormEntryStyle;
break;
}
}
protected void ValidateStyle(Picker control, bool isValid)
{
switch (isValid)
{
case false:
control.Style = ValidationEntryErrorStyle;
break;
default:
control.Style = null;
break;
}
}
#endregion
}
2: ССЫЛКА НА СТРАНИЦУ БАЗОВОГО КЛАССА на своей СТРАНИЦЕ :
Убедитесь, что вы ссылаетесь на свои представления в «xmlns: views». Обратите особое внимание на корневой элемент страницы: «
<?xml version="1.0" encoding="utf-8" ?>
<views:BaseContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:Pulse.Mobile.Views;assembly=Pulse.Mobile"
x:Class="Pulse.Mobile.Views.ShakeoutDocumentPage">
<ContentPage.Content>
// YOUR AWESOME CONTENT GOES HERE...
</ContentPage.Content>
</views:BaseContentPage>
3
Prisoner ZERO
21 Авг 2019 в 18:55
Здесь вы смешиваете две разные вещи: страницу и ячейку просмотра.
И страницы, и ячейки представления могут быть созданы как с помощью кода, так и с использованием XAML, но это разные вещи.
При создании любого компонента в XAML, будь то страница или представление, тип корневого узла должен быть тем типом, который вы подклассифицируете. Затем код, стоящий за файлом .cs, должен быть производным от того же базового класса, в противном случае вы можете полностью исключить базовый класс в выделенном коде, поскольку частичные классы не должны повторно указывать, из какого класса они происходят.
Итак, для определения страницы CashAdvance обязательно удалите часть «: ViewCell» из определения класса в выделенном коде.
Тогда вам, вероятно, следует создать свою страницу в XAML (иначе, в любом случае, какой смысл использовать страницу xaml, если вы создадите ее в коде?)
Если вам действительно нужна настраиваемая ячейка просмотра (например, для использования внутри ListView), создайте другой файл .xaml для своей ячейки просмотра и создайте там собственный пользовательский интерфейс. Затем вы можете ссылаться на него внутри XAML страницы или из внутреннего кода.
Дополнительные сведения об использовании XAML см. На странице Xamarin Документация XAML
1
irreal
12 Май 2016 в 06:44
Как правило, основной тег xaml должен соответствовать наследованию в файле .cs, чтобы предотвратить ошибки различных базовых классов, поэтому, если:
<contentPage xmlns="http://xamarin......> </contentPage >
Тогда файл .cs обычно будет
public partial class myPage : contentPage { ........}
0
A. Almazidi
22 Мар 2019 в 09:05
I have already looked to similar answers and I don’t know why I am still have this error:
Severity Code Description Project File Line Suppression State
Error CS0263 Partial declarations of 'MainPage' must not specify different base classes MyNavDraw.Android (my path ...)MainPage.xaml.cs 13 Active
MainPage.xaml.cs:
namespace MyNavDraw
{
public partial class MainPage : MasterDetailPage
{
...
MainPage.xaml
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyNavDraw"
x:Class="MyNavDraw.MasterDetailPage">
<MasterDetailPage.Master>
...
What I tried so far:
In xaml I have replaced the tag to:
<we:MainPage ...
I checked «x:Class» and I think is correct the syntax, I have restarted the VS and I built again the solution.
I use Xamarin with VS 2017.
After a day (from this post question) I tried to put in comments the code of «MainPage.xaml» file. Then I saved it, I removed comments, saved it again and built the solution. I have a new error in built:
No way to resolve conflict between "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" and "mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e". Choosing "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" arbitrarily.
I have an other problem when I debug the app to my physical phone (android).
In My.Nav.Draw.Droid.MainPage.xaml.g.cs I have an exception Unhandled error.
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(MainPage));
What can be wrong?
created new uap project
added template10 package (1.1.12)
changed App base class from Application to Template10.Common.BootStrapper
buid and get error: error CS0263: Partial declarations of ‘App’ must not specify different base classes
because generated partial app class (App.g.i.cs) derives from Windows.UI.Xaml.Application.
I have no clue why this happens, i was trying to recreate one of the samples.
Anyone any ideas?
@renevangeffen, it seems like you haven’t changed the corresponding XAML file of your App class (App.xaml that is).
It should look like this:
<common:BootStrapper x:Class="{YourProjectNamespace}.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:common="using:Template10.Common"> <!-- Your resources declarations or whatever --> </common:BootStrapper>
After the changes, clean and rebuild solution, the error will go away.
Hope it helps!
@NEKIT-Boss,
Thanks for your reply, I already figured out it should like this, I think I was looking at the wrong sample code. Thanks anyway
@renevangeffen, close the issue then, if everything is OK.
| description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
|---|---|---|---|---|---|
|
Compiler Error CS0263 |
Compiler Error CS0263 |
07/20/2015 |
CS0263 |
CS0263 |
94fe3eb0-10e9-4602-a993-68fe125c8565 |
Compiler Error CS0263
Partial declarations of ‘type’ must not specify different base classes
When defining a type in partial declarations, specify the same base types in each of the partial declarations. For more information, see Partial Classes and Methods.
The following sample generates CS0263:
// CS0263.cs // compile with: /target:library class B1 { } class B2 { } partial class C : B1 // CS0263 – is the base class B1 or B2? { } partial class C : B2 { }
C# Compiler Error
CS0263 – Partial declarations of ‘type’ must not specify different base classes
Reason for the Error
You’ll get this error in your C# code when you have defined the partial type with same name and each one of them has a different base class.
For example, lets try to compile the below code snippet.
using System;
namespace DeveloperPubNamespace
{
public class BaseClass1
{
public string Name { get; set; }
}
public class BaseClass2
{
public string Name { get; set; }
}
public partial class class1 : BaseClass2
{
}
public partial class class1 : BaseClass1
{
}
class Program
{
public static void Main()
{
Console.WriteLine("Welcome");
}
}
}
You’ll receive the error code CS0263 when you try to build the above C# program because you have declared multiple partial types “class1” but each one inheriting from a different base class “BaseClass1” and “BaseClass2”
Error CS0263 Partial declarations of ‘class1’ must not specify different base classes DeveloperPublish C:UsersSenthilsourcereposConsoleApp3ConsoleApp3Program.cs 15 Active

Solution
When you define a type in partial declarations in your C# program, it is important to specify the same base types for each of the partial types.
You can fix the above program by specifying the same base class for both the partial type declarations as shown below.
using System;
namespace DeveloperPubNamespace
{
public class BaseClass1
{
public string Name { get; set; }
}
public class BaseClass2
{
public string Name { get; set; }
}
public partial class class1 : BaseClass1
{
}
public partial class class1 : BaseClass1
{
}
class Program
{
public static void Main()
{
Console.WriteLine("Welcome");
}
}
}
