[英]Bindable property value pass from Child view's bindable property inside parent Page using Xamarin Forms?
我創建了一個具有Image的View(BlankScreen),並在該視圖的后面代碼中創建了BindableProperty圖標。
View的Xaml代碼:
<ContentView
x:Class="Demo.CustomViews.BlankScreen"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<ContentView.Content>
<StackLayout>
<Label Text="Hello Xamarin.Forms!" />
<Image x:Name="image"/>
</StackLayout>
</ContentView.Content>
</ContentView>
查看后面的代碼:
public partial class BlankScreen : ContentView
{
public BlankScreen ()
{
InitializeComponent ();
}
public static readonly BindableProperty IconProperty =
BindableProperty.Create(nameof(Icon), typeof(ImageSource), typeof(BlankScreen), null);
public ImageSource Icon
{
get => (ImageSource)GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
}
然后,我將此視圖用於Page,因此我將此視圖包括在BindableProperty Icon中。
<customviews:BlankScreen Icon="chat" />
但是問題是無法從父頁面的視圖傳遞的我的視圖上設置聊天圖標。
那么我該如何解決這個問題,請幫忙?
我認為它不起作用的原因是您似乎沒有對其進行設置
您的可綁定屬性應如下所示:
public static readonly BindableProperty IconProperty =
BindableProperty.Create(nameof(Icon), typeof(ImageSource), typeof(BlankScreen), null, propertyChanged: IconChanged);
public ImageSource Icon
{
get => (ImageSource)GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
完成后,添加以下方法並更新圖像:
private static void IconChanged(BindableObject bindable, object oldValue, object newValue)
{
BlankScreen screen= bindable as BlankScreen ;
screen.image.Source= newValue.ToString();
}
如有查詢,請通知我
我發現BlankScreen中有圖像,但是您沒有為其設置源。 我為該圖像綁定圖標。
<ContentView.Content>
<StackLayout>
<Label Text="Hello Xamarin.Forms!" />
<Image x:Name="image" Source="{Binding Icon}" />
</StackLayout>
</ContentView.Content>
然后創建propertyChanged事件:
public partial class BlankScreen : ContentView
{
public static readonly BindableProperty IconProperty =
BindableProperty.Create(nameof(Icon), typeof(ImageSource), typeof(BlankScreen), defaultBindingMode: BindingMode.TwoWay,
propertyChanged: (bindable, oldVal, newVal) =>
{
var page = (BlankScreen)bindable;
page.image.Source = (ImageSource)newVal;
});
public ImageSource Icon
{
get => (ImageSource)GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
public BlankScreen ()
{
InitializeComponent ();
}
}
最后,我在Contentpage中使用此自定義視圖。
<ContentPage.Content>
<StackLayout>
<customview:BlankScreen Icon="a1.jpg" />
</StackLayout>
</ContentPage.Content>
它工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.