【问题标题】:How do I add a custom view to stack layout from code behind in Xamarin如何从 Xamarin 中的代码中将自定义视图添加到堆栈布局
【发布时间】:2016-12-27 03:23:52
【问题描述】:

我有一个 Xamarin Forms 组件,它在 Xaml 中有一个 StackLayout。我给了它一个 stackView 的 xName。

我有另一个自定义组件,我想从后面的代码中以编程方式添加到堆栈布局中,但我遇到了错误,我不知道为什么。

我收到的错误是我的自定义登录视图无法转换为 Xamarin.Forms.View

using System;
using System.Collections.Generic;

using Xamarin.Forms;

namespace TechPact
{
    public partial class CustomView : ContentPage
    {
        public CustomView()
        {
            InitializeComponent();
            stackView.Children.Add(new CustomLoginView());
        }
    }
}

这是我的登录视图

?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="TechPact.CustomLoginView">

    <StackLayout>
        <Button Text="Login with Facebook" />
    </StackLayout>
</ContentPage>

这是登录视图的代码

using System;
using System.Collections.Generic;

using Xamarin.Forms;

namespace TechPact
{
    public partial class CustomLoginView : ContentPage
    {
        public TechPactLoginView()
        {
            InitializeComponent();
        }
    }
}

【问题讨论】:

    标签: c# xaml xamarin


    【解决方案1】:

    从 ContentView 而不是 Page 导出 CustomLoginView

    【讨论】:

      【解决方案2】:

      您的 CustomLoginView 是否扩展 ContentView 或其他 Xamarin 表单视图? 如果可以,您发布的代码应该可以工作

      【讨论】:

      • 它扩展了 ContentPage
      • 您的组件应该扩展 ContentView,而不是 ContentPage。您还可以扩展 StackLayout 或 AbsoluteLayout 之类的 Layout,甚至可以扩展 DatePicker 之类的其他 View,您不能做的一件事是扩展 ContentPage。
      【解决方案3】:

      我不确定这是否是 Xamarin Studio 的错误,或者是否将登录视图更改为扩展 ContnetView 而不是 ContentPage,但在我这样做之后它现在正在工作。

      【讨论】:

      • 看看我的回答:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      相关资源
      最近更新 更多