2016-01-31 49 views
0

我目前正在嘗試爲自己創建一個簡單的C++ Windows Phone 8.1應用程序,並且陷入了這個簡單的問題。我找不到任何類似C++代碼的示例,僅適用於C#。C++ XAML從組合框中選擇項目

我的代碼基於簡單的"Hello world"程序。在MainPage.xaml我已經介紹了以下組合框

<ComboBox x:Name="AttackDice" HorizontalAlignment="Left" Height="70" 
       Margin="37,70,0,0" VerticalAlignment="Top" 
       Width="320"> 
     <ComboBoxItem Content="One attack dice"/> 
     <ComboBoxItem Content="Two attack dice" IsSelected="True"/> 
     <ComboBoxItem Content="Three attack dice" /> 
     <ComboBoxItem Content="Four attack dice"/> 
     <ComboBoxItem Content="Five attack dice"/> 
     <ComboBoxItem Content="Six attack dice"/> 
</ComboBox> 

我也有簡單的按鈕,這會觸發以下事件在我Mainpage.xaml.cpp

void HelloWorld::MainPage::RollDice_Button_Click(Platform::Object^ sender, 
    Windows::UI::Xaml::RoutedEventArgs^ e) 
{ 
    AttackResultTextBlock->Text = "Number of dice rolled: " 
+ AttackDice->SelectedItem->ToString(); 
} 

的代碼應該檢索選擇ComboBoxItem,並輸出所選數量的(攻擊)骰子。但是,輸出是:(根據一些指導,我在網上找到)

Windows.UI.Xaml.Controls.ComboBoxItem

在C#中,這樣做是正確的方法

Text = ((ComboBoxItem)AttackDice.SelectedItem).Content.ToString(); 

但我不知道如何在C++中做到這一點。

+1

據推測,這應該是'(safe_cast (AttackDice->的SelectedItem) ) - >的Content>的ToString()'。 – IInspectable

+0

@IInspectable謝謝,這工作!我想你應該把它作爲答案發布,以便我可以接受它。 – Olorun

回答

1

以下C#代碼

Text = ((ComboBoxItem)AttackDice.SelectedItem).Content.ToString(); 

可轉化爲C++/CX。在C#鑄件的等效(見Casting and Type Conversions),其引發在失敗的InvalidCastException,是safe_cast在C++/CX:

Text = (safe_cast<ComboBoxItem^>(AttackDice->SelectedItem))->Content->ToString();