[英]Dynamically switch control type to show different content types
In my app (windows 8.1) I use the split Visual Studio template. 在我的应用程序(Windows 8.1)中,我使用拆分的Visual Studio模板。 It is working and I can show text content if I choose an item.
它正在运行,如果我选择一个项目,我可以显示文本内容。
The content is mixed with text, images, pdfs. 内容与文本,图像,pdf混合在一起。
So how can I dynamically switch the control type (eg TextBlock, Image, UserControl) based an the content data? 那么如何基于内容数据动态切换控件类型(例如TextBlock,Image,UserControl)?
If I get text it should displayed in an TextBlock, but if I get an Image (Link) it should displayed in a image control. 如果我收到文本,它应该显示在TextBlock中,但是如果我收到图像(链接),它应该显示在图像控件中。 (Maybe the way to switch the control type is wrong, I don't know!?)
(也许切换控件类型的方法是错误的,我不知道!?)
Can I solve this in XAML or should I do it in code behind? 我可以在XAML中解决此问题还是应该在后面的代码中解决?
I don't know how can I do this. 我不知道该怎么办。 Can anyone please give me a hint?
谁能给我一个提示吗?
<Grid x:Name="itemDetailGrid" Margin="0,60,0,50">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Source="{Binding ImagePath}" Grid.Row="1" Margin="0,0,20,0" Width="180" Height="180" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
<StackPanel x:Name="itemDetailTitlePanel" Grid.Row="1" Grid.Column="1">
<TextBlock x:Name="itemTitle" Margin="0,-10,0,0" Text="{Binding Title}" Style="{StaticResource SubheaderTextBlockStyle}"/>
<TextBlock x:Name="itemSubtitle" Margin="0,0,0,20" Text="{Binding Subtitle}" Style="{StaticResource SubtitleTextBlockStyle}"/>
</StackPanel>
<!-- <TextBlock Grid.Row="2" Grid.ColumnSpan="2" Margin="0,20,0,0" Text="{Binding Content}" Style="{StaticResource BodyTextBlockStyle}"/> -->
<Image Source="{Binding Content}" Grid.ColumnSpan="2" Grid.Row="2" Margin="0,20,0,0" Stretch="UniformToFill" />
The answer to your question is for you to use DataTemplate
s to define how each data type should be rendered in the UI. 这个问题的答案是让您使用
DataTemplate
定义如何在UI中呈现每种数据类型。 All you need to do is to declare a DataTemplate
for each different data type: 您需要做的就是为每种不同的数据类型声明一个
DataTemplate
:
<DataTemplate DataType="{x:Type System:String}">
<TextBlock Text="{Binding}">
</DataTemplate>
...
<DataTemplate DataType="{x:Type Custom:DataObject}">
<UserControl DataContext="{Binding}">
</DataTemplate>
If you omit the x:Key
references (as in the example above), then the Framework will automatically render the content of the relevant DataTemplate
whenever it comes across one of the specified data types. 如果省略
x:Key
引用(如上例所示),则只要遇到指定的数据类型之一,框架就会自动呈现相关DataTemplate
的内容。 Please see the Data Templating Overview page on MSDN for further details. 有关更多详细信息,请参见MSDN上的“ 数据模板概述”页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.