A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
ImageIcon is a named element inside a ContentView custom control. To set its image from a viewmodel or from the parent view, expose a bindable property on the ContentView and bind the Image.Source to that property, instead of trying to access ImageIcon directly from outside.
- In
TourProductItem.xaml, bind theImageto a property on theContentView:
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TourGrosses.Controls.TourProductItem">
<Grid Padding="10">
<!-- other rows/columns omitted for brevity -->
<Image x:Name="ImageIcon"
Grid.Row="1"
Grid.RowSpan="4"
Grid.Column="0"
Source="{Binding ImageSource, Source={x:Reference this}}" />
<!-- other labels -->
</Grid>
</ContentView>
Make sure the root ContentView has a name so it can be referenced:
<ContentView x:Class="TourGrosses.Controls.TourProductItem"
x:Name="this"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
- In
TourProductItem.xaml.cs, define a bindable property and CLR wrapper:
public partial class TourProductItem : ContentView
{
public static readonly BindableProperty ImageSourceProperty =
BindableProperty.Create(
nameof(ImageSource),
typeof(ImageSource),
typeof(TourProductItem),
default(ImageSource));
public ImageSource ImageSource
{
get => (ImageSource)GetValue(ImageSourceProperty);
set => SetValue(ImageSourceProperty, value);
}
public TourProductItem()
{
InitializeComponent();
}
}
- From the parent page or its viewmodel, set the property instead of the internal
ImageIcon:
<!-- In the parent page XAML -->
<controls:TourProductItem ImageSource="dotnet_bot.png" />
or via binding:
<controls:TourProductItem ImageSource="{Binding ProductImage}" />
This pattern matches how custom controls are built with ContentView: internal elements (like ImageIcon) are not accessed directly from outside; instead, bindable properties are exposed and used for data binding.
References: