2015-07-13 67 views
1

我正在從stackLayout組件創建一個xaml文件inheret。我已經調用了這個TimerButton。引用xaml中xaml.cs文件中的外部堆棧佈局組件ID Xamarin

我有兩個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"; 
} 
+0

那就是我試圖用x:Name來做的事情。但無法在Timerbutton.xaml.cs文件中找到它。 – Reservedeler

+0

那麼,我需要它在按鈕初始化時運行代碼。我想知道它是否是一個鼻菸按鈕或煙霧按鈕,而不必將SmokeTimerButton和SnuffTimerButton分別作爲組件。 – Reservedeler

回答

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參考

+0

這幫了很多。儘管Xamarin使用BindableProperty而不是DependencyProperty和Create來代替註冊。謝謝您的幫助。 – Reservedeler