Mam taki kod:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace App6.Controls
{
public class ImageButtonViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool _Enable { get; set; }
public bool Enable
{
get => _Enable;
set
{
_Enable = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Enable)));
}
}
}
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ImageButton : Grid
{
public static readonly BindableProperty SourceProperty =
BindableProperty.Create("Source", typeof(string), typeof(ImageButton));
public string Source
{
get { return (string)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public static readonly BindableProperty ClickCommandProperty =
BindableProperty.Create("ClickCommand", typeof(ICommand), typeof(ImageButton));
public ICommand ClickCommand
{
get { return (ICommand)GetValue(ClickCommandProperty); }
set { SetValue(ClickCommandProperty, value); }
}
public ImageButton()
{
InitializeComponent();
//this.BindingContext = new ImageButtonViewModel(); //// to powoduje blad
}
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (propertyName == ClickCommandProperty.PropertyName)
{
ClickCommand.CanExecuteChanged += (s, e) =>
{
(this.BindingContext as ImageButtonViewModel).Enable = ClickCommand.CanExecute(null);
};
}
base.OnPropertyChanged(propertyName);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App6.Controls.ImageButton"
xmlns:vm="clr-namespace:App6.Controls"
xmlns:controls="clr-namespace:App6.Controls"
x:Name="this">
<!--To powoduje blad-->
<!--<Grid.BindingContext>
<controls:ImageButtonViewModel />
</Grid.BindingContext>-->
<Button x:Name="B1" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Command="{Binding Source={x:Reference this}, Path=ClickCommand}" />
<Image x:Name="B2" VerticalOptions="Center" HorizontalOptions="Center" Source="{Binding Source, Source={x:Reference this}}" Aspect="AspectFit" Margin="30" >
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding Source={x:Reference this}, Path=ClickCommand}" />
</Image.GestureRecognizers>
</Image>
</Grid>
View model nie jest nigdzie wykorzystywane, ale dodanie go do kodu poprzez xaml lub w c# psuje z jakiegoś powodu działanie kontrolki. Nie reaguje wtedy na ClickCommand. Czym jest to spowodowane i jak prawidłowo dodać viewmodel?