2016-11-29 25 views
0

我們正在利用XamlReader允許用戶在我們的應用程序中動態定義UI。使用用戶自定義代碼的XamlReader動態事件

例如,如果他們想有多個按鈕定義網格,可以通過定義XAML字符串來完成。

var xaml = ` 
<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Height='600' Background='Gray'> 
       <Grid.ColumnDefinitions> 
         <ColumnDefinition Width='2*' /> 
         <ColumnDefinition Width='1*' /> 
         <ColumnDefinition Width='1*' /> 
       </Grid.ColumnDefinitions> 
       <Grid.RowDefinitions> 
         <RowDefinition Height='2*' /> 
         <RowDefinition Height='1*' /> 
         <RowDefinition Height='1*' /> 
       </Grid.RowDefinitions> 
       <TextBlock Name='FirstName' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Text='TESTING' Grid.Row='0' Grid.Column='0' Height='20' /> 
       <TextBox Name='LastName' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Text='TESTING' Grid.Row='1' Grid.Column='0' Height='20' />     
     <Button Grid.Column='1'>Button 2</Button> 
       <Button Grid.Column='2'>Button 3</Button> 
       <Button Grid.Column='1' Grid.Row='1'>Button 5</Button> 
       <Button Grid.Column='2' Grid.Row='1'>Button 6</Button> 
       <Button Grid.Row='2'>Button 7</Button> 
       <Button Grid.Column='1' Grid.Row='2'>Button 8</Button> 
       <Button Grid.Column='2' Grid.Row='2'>Button 9</Button> 
</Grid> 
`; 

var control = Windows.UI.Xaml.Markup.XamlReader.Load(xaml) as UIElement; 

但是,我們也希望用戶能夠定義事件。例如,單擊按鈕1將顯示一個消息框。點擊按鈕2將做其他事情。

我們希望他們能夠指定代碼本身,類似於XamlReader.Load。

有沒有辦法做到這一點?

回答

0

不幸的是沒有。 UWP不允許您在運行時生成或編譯C#代碼。你只能創建簡單的Expression樹,但這對你的情況並不是很有用。

此外,如果你檢查MSDN Documentation,它說

的XAML不應該試圖指定X:Class屬性,或包括事件處理程序的任何XAML定義的屬性

從這一點很明顯,它不是爲此目的而設計的。