【问题标题】:Reference to external stacklayout component ID inside xaml.cs file in xaml Xamarin在 xaml Xamarin 中的 xaml.cs 文件中引用外部 stacklayout 组件 ID
【发布时间】:2015-07-13 06:40:33
【问题描述】:

我正在从 stackLayout 组件生成一个 xaml 文件。我已经调用了这个 TimerButton。

我有两个 TimerButtons,想区分它们。

//In MainPage.xaml   
<component:TimerButton x:Name="Smoke"></component:TimerButton>  
<component:TimerButton x:Name="Snuff"></component:TimerButton>

我需要发送 ID,以便我可以在 TimerButton 组件内的 C# 代码 (ViewModel.TobaccoType) 中设置一个值。我试过使用 x: arguments/name/type 没有运气。

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

if (this.FindByName<TimerButton>("Smoke") != null)
{
     ViewModel.TobaccoType = "Smoke";
}

【问题讨论】:

  • 这就是我试图用 x:Name 做的事情。但无法在 Timerbutton.xaml.cs 文件中访问它。
  • 好吧,我需要它在按钮初始化时运行代码。我想知道它是鼻烟按钮还是烟雾按钮,而不必将 SmokeTimerButton 和 SnuffTimerButton 分别作为组件。

标签: c# xaml xamarin


【解决方案1】:

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

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); }
}

然后你在你的 XAML 中像这样引用它:

//In MainPage.xaml   
<component:TimerButton x:Name="Smoke" TobaccoType="Smoke"></component:TimerButton>  
<component:TimerButton x:Name="Snuff" TobaccoType="Snuff"></component:TimerButton>

您可以在 TimerButton.cs 中轻松引用此属性

【讨论】:

  • 这很有帮助。尽管 Xamarin 使用 BindableProperty 而不是 DependencyProperty 和 Create 而不是 register。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
  • 2010-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多