我有一个 ListBox,其 ItemsSource 绑定到对象列表。列表框有一个 ItemTemplate 和一个包含 TextBlock 的 DataTemplate。文本块的 Text 绑定到对象的 Name 属性(即 Text="{Binding Name}")。
我想提供一个单选按钮来显示同一列表的不同视图。例如,允许用户在“名称”属性和“ID”属性之间切换。
我找到了一个这样的答案2381740 https://stackoverflow.com/questions/2381740/changing-datatemplate-textblock-property-at-runtime但我还在数据模板中设置了边框和文本框样式(请参见下面的代码)。
有没有办法重置 Textblock 绑定?我不想重新创建整个数据模板。实际上我什至不知道如何做到这一点,有没有一种简单的方法可以将 xaml 转换为代码?
谢谢
科迪
<DataTemplate>
<Border Margin="0 0 2 2"
BorderBrush="Black"
BorderThickness="3"
CornerRadius="4"
Padding="3">
<TextBlock Style="{StaticResource listBoxItemStyle}"
Text="{Binding Name}" />
</Border>
</DataTemplate>
Wallstreet Programmer 的解决方案非常适合您,因为您使用的是单选按钮。然而,我认为我应该为这个问题的未来读者提及一个更通用的解决方案。
您可以更改 DataTemplate 以使用普通的“{Binding}”
<DataTemplate x:Key="ItemDisplayTemplate">
<Border ...>
<TextBlock ...
Text="{Binding}" />
</Border>
</DataTemplate>
然后在代码中您不必重新创建完整的 DataTemplate。你所要做的就是重新创建这个:
<DataTemplate>
<ContentPresenter Content="{Binding Name}" ContentTemplate="{StaticResource ItemDisplayTemplate}" />
</DataTemplate>
这很容易:
private DataTemplate GeneratePropertyBoundTemplate(string property, string templateKey)
{
var template = FindResource(templateKey);
FrameworkElementFactory factory = new FrameworkElementFactory(typeof(ContentPresenter));
factory.SetValue(ContentPresenter.ContentTemplateProperty, template);
factory.SetBinding(ContentPresenter.ContentProperty, new Binding(property));
return new DataTemplate { VisualTree = factory };
}
如果您有许多属性,即使在单选按钮示例中,这也特别方便。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)