Reputation: 53
I'm trying to make a custom control with Binding and my Binding of an ImageSource isn't working. That's my code:
Customcontrol.xaml:
<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
x:Class="Custom.CustomEntry"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<ContentView.Content>
<StackLayout Orientation="Vertical">
<ImageButton
BackgroundColor="Transparent"
Clicked="Open"
Source="{Binding Icon}" />
<Frame
x:Name="frameemojis"
BackgroundColor="red"
IsVisible="False">
<Label Text="Hello" />
</Frame>
</StackLayout>
</ContentView.Content>
</ContentView>
public partial class CustomControl: ContentView { public static readonly BindableProperty IconProperty = BindableProperty.Create("Icon", typeof(ImageSource), typeof(CustomControl));
public ImageSource Icon
{
get { return (ImageSource)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
bool state = true;
void Open(object o, System.EventArgs e)
{
if (state)
{
state = false;
frameemojis.IsVisible = true;
}
else
{
state = true;
frameemojis.IsVisible = false;
}
}
public CustomControl()
{
InitializeComponent();
}
}
}
MainPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="App23.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:fav="clr-namespace:Custom;assembly=Custom">
<StackLayout>
<fav:CustomControl Icon="icon.png" WidthRequest="200" />
</StackLayout>
</ContentPage>
MainPage.xaml.cs:
public partial class MainPage : ContentPage
{
public MainPage()
{
BindingContext = new ViewModel();
InitializeComponent();
}
}
The ViewModel now is empty but in the future I will use it to control other things. My idea is to set the icon in the MainPage with Icon="icon.png". Any idea why isn't working?
Upvotes: 0
Views: 220
Reputation: 18861
You could modify the code of Custom View like following .
<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
x:Class="Custom.CustomEntry"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="CustomView" //set name of custom view
>
<ContentView.Content>
<StackLayout Orientation="Vertical">
<ImageButton
BackgroundColor="Transparent"
Clicked="Open"
Source="{Binding Source={x:Reference CustomView},Path=Icon}" />
<Frame
x:Name="frameemojis"
BackgroundColor="red"
IsVisible="False">
<Label Text="Hello" />
</Frame>
</StackLayout>
</ContentView.Content>
</ContentView>
Upvotes: 0
Reputation: 2299
From documentation
The naming convention for bindable properties is that the bindable property identifier must match the property name specified in the Create method, with "Property" appended to it.
So you should rename LeftSideIconProperty
to IconProperty
or Icon
to LeftSideIcon
.
Upvotes: 0