C# 对xaml Xamarin中xaml.cs文件内外部stacklayout组件ID的引用

C# 对xaml Xamarin中xaml.cs文件内外部stacklayout组件ID的引用,c#,xaml,xamarin,C#,Xaml,Xamarin,我正在从stackLayout组件中生成一个xaml文件。我已经叫了这个时间按钮 我有两个TimerButton,想区分它们 //In MainPage.xaml <component:TimerButton x:Name="Smoke"></component:TimerButton> <component:TimerButton x:Name="Snuff"></component:TimerButton> //在MainPage.

我正在从stackLayout组件中生成一个xaml文件。我已经叫了这个时间按钮

我有两个TimerButton,想区分它们

//In MainPage.xaml   
<component:TimerButton x:Name="Smoke"></component:TimerButton>  
<component:TimerButton x:Name="Snuff"></component:TimerButton>
//在MainPage.xaml中
我需要发送ID,以便在TimerButton组件内的C#code(ViewModel.TobaccoType)中设置一个值。我尝试过使用x:arguments/name/type,但没有成功

//In TimerButton.xaml.cs
ViewModel = new TimerButtonViewModel();

if (this.FindByName<TimerButton>("Smoke") != null)
{
     ViewModel.TobaccoType = "Smoke";
}
//在TimerButton.xaml.cs中
ViewModel=new TimerButtonViewModel();
if(this.FindByName(“Smoke”)!=null)
{
ViewModel.TobaccoType=“烟雾”;
}

您可以执行以下操作。给TimerButton一个所谓的如下所示:

public static readonly DependencyProperty TobaccoTypeProperty = 
    DependencyProperty.Register(
    "TobaccoType", typeof(String),
    typeof(TimerButton), null);

public String TobaccoType
{
   get { return (String)GetValue(TobaccoTypeProperty); }
   set { SetValue(TobaccoTypeProperty, value); }
}
//In MainPage.xaml   
<component:TimerButton x:Name="Smoke" TobaccoType="Smoke"></component:TimerButton>  
<component:TimerButton x:Name="Snuff" TobaccoType="Snuff"></component:TimerButton>
然后在XAML中引用它,如下所示:

public static readonly DependencyProperty TobaccoTypeProperty = 
    DependencyProperty.Register(
    "TobaccoType", typeof(String),
    typeof(TimerButton), null);

public String TobaccoType
{
   get { return (String)GetValue(TobaccoTypeProperty); }
   set { SetValue(TobaccoTypeProperty, value); }
}
//In MainPage.xaml   
<component:TimerButton x:Name="Smoke" TobaccoType="Smoke"></component:TimerButton>  
<component:TimerButton x:Name="Snuff" TobaccoType="Snuff"></component:TimerButton>
//在MainPage.xaml中

您可以在TimerButton.cs中轻松引用这些属性,这就是我尝试使用x:Name所做的。但是无法在Timerbutton.xaml.cs文件中找到它。我需要它在按钮初始化时运行代码。我想知道它是一个snuff按钮还是smoke按钮,而不需要将SmokeTimerButton和SnuffTimerButton分别作为组件。这很有帮助。虽然Xamarin使用BindableProperty而不是DependencyProperty,并使用Create而不是register。谢谢你的帮助。