【发布时间】:2017-03-17 00:29:12
【问题描述】:
我正在尝试通过引用 dll 来使用在解决方案之外定义的用户控件。如果我使用代码,它就可以工作;但不是 XAML
这里是代码 - 1.用户控制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Internals;
namespace ComplexControl
{
[Preserve]
public class ComplexControl : ContentView
{
public ComplexControl()
{
var button = new Button
{
Text = "Click Me!",
//VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
};
int clicked = 0;
button.Clicked += (s, e) => button.Text = "Clicked: " + clicked++;
Content = button;
}
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
class PreserveAttribute : Attribute { }
}
}
- 对于项目中的使用,我在 PCL 中引用了程序集 ConplexControl
它适用于代码(即不使用 XAML)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using ComplexControl;
namespace CustomControlUsageExample
{
public partial class MainPage : ContentPage
{
public MainPage()
{
// without InitializeComponent(); works
//this way works
//Step 1.
StackLayout sl = new StackLayout();
Label lb = new Label();
lb.Text = "Hello";
sl.Children.Add(lb);
sl.Children.Add(new ComplexControl.ComplexControl());
Content = sl;
}
}
}
如果我与 XAML 一起使用,它不起作用
这样
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"
xmlns:local="clr-namespace:CustomControlUsageExample"
x:Class="CustomControlUsageExample.MainPage"
xmlns:custom="clr-namespace:ComplexControl;assembly:ComplexControl">
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Label Text="Welcome to Xamarin Forms!"/>
<custom:ComplexControl.ComplexControl/>
</StackLayout>
</ContentPage>
背后的代码是
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using ComplexControl;
namespace CustomControlUsageExample
{
public partial class MainPage : ContentPage
{
public MainPage()
{
//This way does not work
//Step 2
InitializeComponent();
}
}
}
我已经尝试过调试,但没有看到它将用户控件添加到内容中。
谁能帮我看看我做错了什么? 如果我不使用 XAML 作为自定义控件,它是有效的。
我正在使用代码完成 userControl 的用户控件工作;但它会被 XAML 中的项目引用。
谢谢,
【问题讨论】:
-
App.xaml.cs 有这个 sn-p 的代码。只是需要
public App() { InitializeComponent(); MainPage = new CustomControlUsageExample.MainPage(); }
标签: xaml xamarin user-controls portable-class-library