Reputation: 63
I want to create a custom control that can let users add any view to a specific location, like below:
MyCustomControl.xaml
<ContentView ...>
<!-- My customizations ... -->
<StackLayout>
<!-- Everything added by user should goes here -->
</StackLayout>
<!-- My other customizations ... -->
</ContentView>
When using it:
<ContentPage>
<controls:MyCustomControl>
<Label />
<Image />
...
<controls:MyCustomControl>
</ContentPage>
How can I do this?
Upvotes: 0
Views: 384
Reputation: 624
I'm going to post one way of doing this here but there are others. From your question, I'm assuming you want to reuse a ContentView in various places and be allowed to change a part of that content view when you instantiate it. I'm going to assume you are going to specify the custom part in XAML. You can use the following pattern to achieve this:
Create your ContentView and add a bindable property for the custom part:
ContentViewWithCustomPart.xaml
<ContentView.Content>
<StackLayout>
<Label Text="I'm always here!" />
<StackLayout x:Name="StackToHoldCustomStuff">
<!-- Stuff goes here injected by bindable property -->
</StackLayout>
</StackLayout>
</ContentView.Content>
ContenViewWithCustomPart.xaml.cs
public partial class ContentViewWithCustomPart : ContentView
{
public static readonly BindableProperty CustomViewProperty =
BindableProperty.Create(nameof(CustomView), typeof(View), typeof(ContentViewWithCustomPart), propertyChanged: OnViewChanged);
static void OnViewChanged(object bindable, object oldValue, object newValue)
{
var page = (ContentViewWithCustomPart)bindable;
page.StackToHoldCustomStuff.Children.Clear();
if (newValue != null) page.StackToHoldCustomStuff.Children.Add((View)newValue);
}
public View CustomView { get => (View)GetValue(CustomViewProperty); set => SetValue(CustomViewProperty, value); }
public ContentViewWithCustomPart()
{
InitializeComponent();
}
}
Usage in a demo page:
<ContentPage.Content>
<StackLayout>
<cv:ContentViewWithCustomPart>
<cv:ContentViewWithCustomPart.CustomView>
<Label Text="I'm a custom bit!" />
</cv:ContentViewWithCustomPart.CustomView>
</cv:ContentViewWithCustomPart>
</StackLayout>
</ContentPage.Content>
Result:
Upvotes: 1