【发布时间】:2014-04-09 00:09:22
【问题描述】:
如果有人知道使用数据相关 (DataContext="{Binding User}") 或静态数据 (DataContext="{Binding User, Source={StaticResource Locator}}") 创建动态 xaml 的解决方案?
这样的解决方案可以保存在控件隐藏和附加字段(Visibility="{Binding IsAnonim, Converter={StaticResource VisibilityConverter}}")上。而且 XAML 必须只满足这种情况下需要的内容,并且不会充满不必要的控件。
可以在渲染时刻执行的代码(“if (IsUser) { }”)。
下面的例子:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" DataContext="{Binding User}">
<StackPanel>
<? if (IsUser) { ?>
<TextBox Text="{Binding UserName, Mode=TwoWay}" />
<PasswordBox Text="{Binding UserPass, Mode=TwoWay}" />
<? } else if (IsAnonim) { ?>
<TextBox Text="{Binding AnonimName, Mode=TwoWay}" />
<? } ?>
<TextBox Text="{Binding MsgText, Mode=TwoWay}" />
<Button Content="Button" Command="{Binding PostCommand}" />
</StackPanel>
</Grid> </UserControl>
附:其他解决方案是可能的。谢谢。
【问题讨论】:
-
如果您的
User属性中有不同类型的对象,您可以使用不同的DataTemplate 并适当地设置它们的DataType。否则,在其ContentTemplateSelector属性中使用带有适当 DataTemplateSelector 的 ContentControl。您可以查看 MSDN 上的Data Templating Overview 文章。 -
我得写两个模板。我正在这样做,它很耗时。
标签: wpf silverlight xaml dynamic interface