如何在XAML中制作并重复使用组件?

5

我决定在Angular中将控件制作成指令以便重复使用,但目前只实现了广告。

namespace Chainhub.Forms.UI.Controls
{
    public partial class BoxPickerControl : ContentView
    {
        public BoxPickerControl()
        {
           InitializeComponent();
        }
    }
}
示例中的BoxPickerControl
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Chainhub.Forms.UI.Controls.BoxPickerControl">
  <StackLayout>
    <StackLayout>
    <StackLayout  BackgroundColor="#383940" Padding="5,5,5,5"  Orientation="Horizontal">
      <StackLayout  HorizontalOptions="StartAndExpand">
        <Label Text="Categories"   TextColor="White"></Label>
      </StackLayout>
</ContentView>

在内容页面中注册并调用

<controls:BoxPickerControl>
</controls:BoxPickerControl>

并成功捕获


目标调用异常


我做错了什么吗?

1个回答

3
为了创建可重用的控件,您应该创建一个UserControl,然后在其中添加一些必要的控件。例如,我们正在创建一个名为FooUserControlUserControl
<UserControl x:Class="OpenExcelFileAndConvertToArray.FooUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:OpenExcelFileAndConvertToArray"
         mc:Ignorable="d">
   <Grid>
       <StackPanel Orientation="Horizontal">
           <TextBlock Text="SomeText"/>
           <Button Content="Delete"/>
       </StackPanel>            
   </Grid>
</UserControl>

然后在任何其他控件中,您都可以重复使用此 FooUserControl。例如:

<Window x:Class="OpenExcelFileAndConvertToArray.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:OpenExcelFileAndConvertToArray"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>        
    <StackPanel>            
        <ComboBox Text="qq" Name="comboBox">
            <ComboBoxItem Content="1"/>
            <ComboBoxItem Content="2"/>
            <ComboBoxItem Content="3"/>
        </ComboBox>
        <!--reusable control-->
        <local:FooUserControl/>            
    </StackPanel>
</Grid>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接