![](/img/trans.png)
[英]How to access method from view inside a Xamarin Forms custom renderer?
[英]How to access fields or controls of Custom View from another Page's XAML in Xamarin Forms?
我有一個自定義控件,我想從將要使用它的頁面中添加一些元素。
像這樣
<Label>
<Label.Text>First Name</Label.Text>
</Label>
如這里, Label
是預定義的,並且Label
的 Text 屬性被添加到其他頁面即。 在使用它的地方,我想添加控件,其值將從另一個將使用它的頁面分配。
這是我在 XAML (DialogView.xaml) 中的自定義控件
<?xml version="1.0" encoding="UTF-8"?>
<ContentView ...>
<ContentView.Content>
<Frame x:Name="dialogContainer" Padding="0" BackgroundColor="Transparent">
<!--I want to use this StackLayout below and add controls inside it from other Page's XAML-->
<StackLayout x:Name="ChildStackLayout" x:FieldModifier="public" />
</Frame>
</ContentView.Content>
</ContentView>
下面是我如何使用它 (MainPage.xaml)
<controls:DialogView>
<controls:DialogView.ChildStackLayout>
<!--Here I want to add controls in my Custom Control-->
<Label Text="Hello, this is a custom dialog" />
</controls:DialogView.ChildStackLayout>
</controls:DialogView>
但是ChildStackLayout
在其他Page中是訪問不到的
xaml中自定義控件的子布局控件不能通過name屬性直接添加新控件。
首先,您可以在 page.cs 中添加新控件。 如:
//declare the content view in the xaml
<control:CustomView x:Name="customview">
//add children control
customview.ChildStackLayout.Children.Add(new Label() { Text = "hello"});
在自定義控件的代碼后面添加一個公共屬性,比如DialogContent
(而不是ChildStackLayout
),就像您的情況一樣。 現在添加一個BindableProperty
來綁定它。 然后使用它的Property Changed 。
在自定義控件的 C# 代碼后面:
public partial class DialogView : Dialog // Dialog inherits ContentView
{
public Layout DialogContent { get => (Layout)GetValue(DialogContentProperty); set => SetValue(DialogContentProperty, value); }
public static readonly BindableProperty DialogContentProperty = BindableProperty.Create(nameof(DialogContent), typeof(Layout), typeof(DialogView), propertyChanged: DialogContentPropertyChanged);
public static void DialogContentPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (DialogView)bindable;
control.dialog.Content = newValue as Layout;
}
}
DialogContent
屬於Layout
類型,因為通常一個對話框會包含多個元素,因此您可以使用任何布局,如StackLayout
或其他一些布局。 並且所有布局都繼承自Layout
,因此,您可以為對話框的內容使用任何布局。
現在當你想使用這個自定義控件時,你可以將它的內容嵌套在父級 xaml 中,就像你想做的那樣。
<controls:DialogView>
<controls:DialogView.DialogContent>
<StackLayout Padding="10" Spacing="10">
<Label Text="Hello, this is a custom dialog" />
<Button Text="OK" />
</StackLayout>
</controls:DialogView.DialogContent>
</controls:DialogView>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.