有什么方法可以在不使用继承的情况下将属性带入类?

时间:2018-09-21 18:33:03

标签: c# xamarin xamarin.forms

我正在使用Xamarin,它要求我的CS类和XAML像这样从Xamarin对象继承:

CS

conn.Open();
cmd.CommandText = cmdStr;
cmd.CommandType = CommandType.Text;

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(/*remove cmdStr and conn from here*/);

//----
da.SelectCommand = cmd;
//----

cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int)).Value = Convert.ToInt32(TB_PatientID.Text);

da.Fill(ds, "dsTable1");

XAML

namespace Japanese.Templates
{
    public partial class TimeIntervalTemplate : ContentView
    {
        public TimeIntervalTemplate()
        {
            InitializeComponent();
        }

        // All my time templates contain this and I would
        // like to not have to repeat these many times in 
        // each time template
        public static readonly BindableProperty SelectedValProperty =
           BindableProperty.Create(
               "SelectedVal", typeof(string), typeof(CardOrderTemplate),
               defaultBindingMode: BindingMode.TwoWay,
               defaultValue: default(string));

        // All my time templates contain this and I would
        // like to not have to repeat these many times in 
        // each time template
        public string SelectedVal
        {
            get { return (string)GetValue(SelectedValProperty); }
            set { SetValue(SelectedValProperty, value); }
        }

但是在许多不同的类中使用了相同的属性和对象:

我想做的就是简单地创建一个从Content视图继承的BaseTemplate类。向其添加属性,然后让TimeIntervalTemplate从BaseTemplate继承。但是,当我这样做时:

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:local="clr-namespace:Japanese;assembly=Japanese" 
             xmlns:b="clr-namespace:Behaviors;assembly=Behaviors" 
             x:Class="Japanese.Templates.TimeIntervalTemplate" x:Name="this">
    <StackLayout BackgroundColor="#FFFFFF" Padding="20,0" HeightRequest="49" Margin="0">

然后它告诉我我不能执行此操作,因为部分类必须继承自同一基类。

有什么办法解决吗?无论如何,我可以在不继承基类的情况下添加诸如public class BaseTemplate : ContentView ... public partial class TimeIntervalTemplate : BaseTemplate ... ..之类的属性?

1 个答案:

答案 0 :(得分:1)

您看到该错误的原因仅在于代码隐藏中的基类类型与XAML中使用的基类类型不同。

一旦确保两个基类类型相同-XAML编译器将很高兴。

<?xml version="1.0" encoding="UTF-8"?>
<!-- make sure change root tag from ContentView to base class type -->
<!-- ('jt' represents the tag prefix for xmlms namespace declaration) -->

<jt:BaseTemplate xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:jt="clr-namespace:Japanese.Templates"

    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    xmlns:local="clr-namespace:Japanese;assembly=Japanese" 
    xmlns:b="clr-namespace:Behaviors;assembly=Behaviors" 
    x:Class="Japanese.Templates.TimeIntervalTemplate" x:Name="this">

    <!-- your content here -->

</jt:BaseTemplate>