如何将此.XAML代码转换为C#代码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将此.XAML代码转换为C#代码相关的知识,希望对你有一定的参考价值。
我需要一些帮助将下面的.XAML代码转换为相应的C#代码:
<ContextMenu x:Name="MenuImageContextMenu" Background="White" Width="175" Height="100">
<ContextMenu.Template>
<ControlTemplate>
<Grid x:Name="ContextMenuGrid" Background="{TemplateBinding Background}">
<Grid x:Name="BeverageGrid" Background="{TemplateBinding Background}" Height="50">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="3.5*" />
<ColumnDefinition Width="6*" />
</Grid.ColumnDefinitions>
<Image x:Name="BeverageImage" Grid.Column="1" Grid.RowSpan="3" Source="/DinerPOS;component/Resources/Images/Restaurant/Beverages/Beverage.png" Stretch="Fill" />
<TextBlock x:Name="BeverageLabel" Grid.Column="2" Grid.RowSpan="3" Text="Beverages" HorizontalAlignment="Center" TextAlignment="Center" VerticalAlignment="Center" />
</Grid>
</Grid>
</ControlTemplate>
</ContextMenu.Template>
</ContextMenu>
到目前为止我尝试过的
ContextMenu ContextMenu = new ContextMenu();
ControlTemplate ControlTemplate = new ControlTemplate();
// ControlTemplate.VisualTree = Grid ????
ContextMenu.Name = MenuImageContextMenu;
ContextMenu.Template = ControlTemplate;
但我不知道如何将主网格ContextMenuGrid
添加到ControlTemplate
。
答案
您可以使用XamlReader.Parse
从XAML字符串创建ContextMenu
元素:
const string Xaml = "<ContextMenu xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" " +
"Background="White" Width="175" Height="100"> " +
" <ContextMenu.Template> " +
" <ControlTemplate> " +
" <Grid x:Name="ContextMenuGrid" Background="{TemplateBinding Background}"> " +
" <Grid x:Name="BeverageGrid" Background="{TemplateBinding Background}" Height="50"> " +
" <Grid.ColumnDefinitions> " +
" <ColumnDefinition Width="0.5*" /> " +
" <ColumnDefinition Width="3.5*" /> " +
" <ColumnDefinition Width="6*" /> " +
" </Grid.ColumnDefinitions> " +
" <Image Grid.Column="1" Grid.RowSpan="3" Source="/DinerPOS;component/Resources/Images/Restaurant/Beverages/Beverage.png" Stretch="Fill" /> " +
" <TextBlock Grid.Column="2" Grid.RowSpan="3" Text="Beverages" HorizontalAlignment="Center" TextAlignment="Center" VerticalAlignment="Center" /> " +
" </Grid> " +
" </Grid> " +
" </ControlTemplate> " +
" </ContextMenu.Template> " +
"</ContextMenu>";
ContextMenu ct = XamlReader.Parse(Xaml) as ContextMenu;
以上是关于如何将此.XAML代码转换为C#代码的主要内容,如果未能解决你的问题,请参考以下文章