c# – 如何制作组件,然后在XAML中重用?

我决定进行控制,然后重复使用.作为角度的指令.

但只能达到广告.

namespace Chainhub.Forms.UI.Controls
{
    public partial class BoxPickerControl : ContentView
    {
        public BoxPickerControl()
        {
           InitializeComponent();
        }
    }
}

例如,在xaml中的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>

并成功抓住了

target invocation exception

我做错了什么?

最佳答案 要创建可重用控件,您应该创建UserControl,然后在UserControl中添加一些必要的控件.例如,我们正在创建UserControl,它将被称为FooUserControl:

<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>
点赞