Чтобы это работало, вам нужно сделать всего пару изменений.
Сначала в файле класса ContenView удалите строку BindingContext = this;
.
Затем вам нужно будет добавитьPropertyChanged
обработчики для вашего BindableProperty
public static readonly BindableProperty ImageSource2Property =
BindableProperty.Create(nameof(ImageSource2),
typeof(string),
typeof(HeaderTemplate),
defaultValue: default(string),
propertyChanged: OnImageSourcePropertyChanged);
public static readonly BindableProperty ImageSource2TapCommandProperty =
BindableProperty.Create(
propertyName: nameof(ImageSource2TapCommand),
returnType: typeof(ICommand),
declaringType: typeof(HeaderTemplate),
defaultValue: default(ICommand),
propertyChanged: OnTapCommandPropertyChanged);
Если вы не можете заметить разницу, я говорю об этом: OnImageSourcePropertyChanged
и OnTapCommandPropertyChanged
.Другие изменения в методе Create не нужны. Я просто добавил propertyName, чтобы он был более понятным.
Конечно, вам нужно реализовать эти два метода:
static void OnTapCommandPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
if(bindable is HeaderTemplate headerTemplate && newValue is ICommand command)
{
headerTemplate.ImageSource2TapCommand = command;
}
}
static void OnImageSourcePropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
if (bindable is HeaderTemplate headerTemplate && newValue is string imageSource)
{
headerTemplate.ImageSource_2.Source = ImageSource.FromFile(imageSource);
}
}
С этими изменениями вы должныиметь возможность нажимать на Image
и перемещаться по своему усмотрению.
Причина, по которой?
Поскольку вы привязываете значения на своей "главной странице" к своему пользовательскому элементу управления, когда последнийСначала созданы следующие значения: null
, поэтому вам необходимо прослушать изменения значений, и это возможно, добавив реализацию onPropertyChanged
в методы Create.
Здесь также есть очень хорошее объяснение. этот пост.
Ваш полный класс должен выглядеть примерно так:
public partial class HeaderTemplate : ContentView
{
public HeaderTemplate()
{
InitializeComponent();
}
public static readonly BindableProperty ImageSource2Property =
BindableProperty.Create(nameof(ImageSource2),
typeof(string),
typeof(HeaderTemplate),
defaultValue: default(string),
propertyChanged: OnImageSourcePropertyChanged);
public string ImageSource2
{
get => (string)GetValue(ImageSource2Property);
set => SetValue(ImageSource2Property, value);
}
public static readonly BindableProperty ImageSource2TapCommandProperty =
BindableProperty.Create(
propertyName: nameof(ImageSource2TapCommand),
returnType: typeof(ICommand),
declaringType: typeof(HeaderTemplate),
defaultValue: default(ICommand),
propertyChanged: OnTapCommandPropertyChanged);
public ICommand ImageSource2TapCommand
{
get => (ICommand)GetValue(ImageSource2TapCommandProperty);
set => SetValue(ImageSource2TapCommandProperty, value);
}
private void ImageSource2_Tapped(object sender, EventArgs e)
{
if (ImageSource2TapCommand == null) return;
if (ImageSource2TapCommand.CanExecute(null))
{
ImageSource2TapCommand.Execute(null);
}
}
static void OnTapCommandPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
if(bindable is HeaderTemplate headerTemplate && newValue is ICommand command)
{
headerTemplate.ImageSource2TapCommand = command;
}
}
static void OnImageSourcePropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
if (bindable is HeaderTemplate headerTemplate && newValue is string imageSource)
{
headerTemplate.ImageSource_2.Source = ImageSource.FromFile(imageSource);
}
}
}
Надеюсь, это поможет .-
Примечание: попробуйте выполнитьПример, размещенный в одном из ответов, для изменения вашего TapEvent с помощью свойства Command.