Xaml 如何在另一个ContentView中查找元素?
在MainPage.xaml中,我有:Xaml 如何在另一个ContentView中查找元素?,xaml,xamarin,xamarin.forms,Xaml,Xamarin,Xamarin.forms,在MainPage.xaml中,我有: <local:MyButton x:Name="btnStart" Text="START" Image="Icon.png" HorizontalOptions="Center" WidthRequest="300" HeightRequest="70"></local:MyButton> 那么,我如何访问“按钮” 我已尝试此操作,但返回空值: btnStart.FindByName<Button>("button"
<local:MyButton x:Name="btnStart" Text="START" Image="Icon.png" HorizontalOptions="Center" WidthRequest="300" HeightRequest="70"></local:MyButton>
那么,我如何访问“按钮”
我已尝试此操作,但返回空值:
btnStart.FindByName<Button>("button").Clicked += btnStartClick;
btnStart.FindByName(“按钮”)。单击+=btnStart单击;
Perharps我需要在与构造函数不同的特定事件中添加上面的代码吗
任何其他建议,以帮助我揭露点击事件,将不胜感激。
谢谢。选项1
可以在自定义控件中公开事件
public event EventHandler ButtonClickEvent;
步骤:
public event EventHandler ButtonClickEvent;
<ContentView.Content>
<Grid x:Name="mainContainer">
<Button x:Name="button" Text="TEMP" Clicked="Button_Clicked"></Button>
<Image x:Name="image" HorizontalOptions="End" Margin="0,15,15,15" Aspect="AspectFill"></Image>
</Grid>
<local:MyButton
ButtonClickEvent="OnButtonClick" />
用法
public partial class MyButton : ContentView
{
public MyButton()
{
InitializeComponent();
//create binding between parent control and child controls
btn.SetBinding(Button.CommandProperty, new Binding(nameof(ClickCommand), source: this));
}
public static readonly BindableProperty ClickCommandProperty =
BindableProperty.Create(
"ClickCommand", typeof(ICommand), typeof(MyButton),
defaultValue: null);
public ICommand ClickCommand
{
get { return (ICommand)GetValue(ClickCommandProperty); }
set { SetValue(ClickCommandProperty, value); }
}
}
<local:MyButton
ClickCommand="{Binding OnTapCommand}" />
您真的应该在MyButton上公开自定义事件。MainPage不需要了解MyButton类的任何内部内容。这是一个很好的观点。我想知道怎么做。一个教程链接会对我有所帮助。谢谢,但是我很难调用Invoke方法,因为我的“ButtonClickEvent”总是空的。有任何线索吗?按钮ClickEvent
将不会为空-如果您为其分配一个事件处理程序(如步骤4所述),哦,那是我的错误。我将事件添加到另一个按钮。令人惊叹的谢谢
public partial class MyButton : ContentView
{
public MyButton()
{
InitializeComponent();
//create binding between parent control and child controls
btn.SetBinding(Button.CommandProperty, new Binding(nameof(ClickCommand), source: this));
}
public static readonly BindableProperty ClickCommandProperty =
BindableProperty.Create(
"ClickCommand", typeof(ICommand), typeof(MyButton),
defaultValue: null);
public ICommand ClickCommand
{
get { return (ICommand)GetValue(ClickCommandProperty); }
set { SetValue(ClickCommandProperty, value); }
}
}
<local:MyButton
ClickCommand="{Binding OnTapCommand}" />