【问题标题】:Is there any way I can bring properties into a Class without using Inheritance?有什么方法可以在不使用继承的情况下将属性带入类?
【发布时间】:2018-09-22 03:04:26
【问题描述】:

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

CS

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); }
        }

XAML

<?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">

但是这里的相同属性和对象用于许多不同的类:

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

public class BaseTemplate : ContentView
... 

public partial class TimeIntervalTemplate : BaseTemplate
...

然后它告诉我我不能这样做,因为部分类必须从同一个基类继承。

有没有办法解决这个问题?无论如何,我可以添加诸如SelectedValProperty .. 之类的属性,而无需从基类继承?

【问题讨论】:

标签: c# xamarin xamarin.forms


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 2010-12-24
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多