我是 Xamarin 的新手。我決定我的第一個專案是健身應用程式。我想要一個自定義控制元件,一個帶有按鈕和標簽的影像,所以我在內容視圖檔案中執行了此操作:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Fitness_App.TabWorkout">
<RelativeLayout >
<Image x:Name="img" Source="workout"/>
<Button BackgroundColor= "Wheat"
CornerRadius="30"
WidthRequest="50"
HeightRequest="50"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView, ElementName=img, Property=Width, Factor=0.68}"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=img, Property=Height, Factor=0.45}"/>
<Label x:Name="workout_name"
FontFamily="BebasNeue"
TextColor ="ForestGreen"
FontSize="37"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView, ElementName=img, Property=Width, Factor=0.18}"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=img, Property=Height, Factor=0.2}"/>
</RelativeLayout>
</ContentView>
因為我想要 5 次鍛煉(針對 5 個肌肉群),所以我把它放在我的頁面中:
<ContentPage.Content>
<ScrollView>
<StackLayout>
<local:TabWorkout/>
<local:TabWorkout/>
<local:TabWorkout/>
<local:TabWorkout/>
<local:TabWorkout/>
</StackLayout>
</ScrollView>
</ContentPage.Content>
這就是它的外觀: android 模擬器 我已經閱讀了有關可系結屬性的資訊,但我不知道在這種情況下它們將如何幫助我。我不知道為什么我的影像的寬度不完整。當我剛剛放置時我的堆疊布局中的影像,它似乎有效。也許你們對此有其他想法?謝謝。
uj5u.com熱心網友回復:
我已經閱讀了可系結屬性,但我不知道在這種情況下它們將如何幫助我。
這里我們為Image控制元件添加了 bindable 屬性,方法與Label.
定義
BindableProperty自定義控制。在
propertyChanged回呼中設定影像源。在 xaml 中分配值。
[XamlCompilation(XamlCompilationOptions.Compile)] public partial class TabWorkout : ContentView { public TabWorkout() { InitializeComponent(); } public static readonly BindableProperty ImageNameProperty = BindableProperty.Create("ImageName", typeof(string), typeof(TabWorkout), propertyChanged: OnEventNameChanged); public string ImageName { get { return (string)GetValue(ImageNameProperty); } set { SetValue(ImageNameProperty, value); } } static void OnEventNameChanged(BindableObject bindable, object oldValue, object newValue) { if(newValue != null) { var control = (TabWorkout)bindable; control.img.Source = ImageSource.FromFile(newValue as string); } } }<ScrollView> <StackLayout> <local:TabWorkout ImageName="a.jpg"/> <local:TabWorkout ImageName="b.png"/> <local:TabWorkout ImageName="c.png"/> <local:TabWorkout ImageName="d.png"/> </StackLayout> </ScrollView>
我不知道為什么我的影像的寬度不完整。
設定Aspect為Fill應該可以解決問題。
<Image x:Name="img" Aspect="Fill"/>
更新
對于可系結屬性,您不僅可以像普通屬性欄位一樣直接賦值,還可以在其上創建系結。
<ScrollView>
<StackLayout>
<local:TabWorkout ImageName="{Binding ImageName}"/>
<local:TabWorkout ImageName="a.jpg"/>
</StackLayout>
</ScrollView>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/361150.html
