在 WPF 中,如何更改代码中 DataTemplate 的 Textblock 的文本绑定?
我有一个 ListBox,其 ItemsSource 绑定到对象列表。列表框有一个 ItemTemplate 和一个包含 TextBlock 的 DataTemplate。文本块的 Text 绑定到对象的 Name 属性(即 Text="{Binding Name}")。
我想提供一个单选按钮来显示同一列表的不同视图。例如,允许用户在“名称”属性和“ID”属性之间切换。
我在 2381740 找到了一个答案,但我也有边框和数据模板中设置的文本框样式(参见下面的代码)。
有没有办法重置 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>
I have a ListBox whose ItemsSource is bound to a list of objects. The Listbox has a ItemTemplate with a DataTemplate containing a TextBlock. The textblock's Text is bound to the object's Name property (i.e. Text="{Binding Name}").
I would like to provide a radio button to show different views of the same list. For example allow a user to toggle between the Name property and an ID property.
I found a SO answer for this at 2381740 but I also have border and a textbox style set in data template (see code below).
Is there anyway to just reset the Textblock binding? I don't want to have to recreate the entire datatemplate. Actually I'm not even sure how to do that, is there an easy way to translating xaml to code?.
Thanks
Cody
<DataTemplate>
<Border Margin="0 0 2 2"
BorderBrush="Black"
BorderThickness="3"
CornerRadius="4"
Padding="3">
<TextBlock Style="{StaticResource listBoxItemStyle}"
Text="{Binding Name}" />
</Border>
</DataTemplate>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Wallstreet Programmer 的解决方案非常适合您,因为您使用的是单选按钮。然而,我认为我应该为这个问题的未来读者提及一个更通用的解决方案。
您可以更改 DataTemplate 以使用普通的“{Binding}”,
然后在代码中您不必重新创建完整的 DataTemplate。您所要做的就是重新创建这个:
这很容易:
如果您有很多属性,即使在单选按钮示例中,这也特别方便。
Wallstreet Programmer's solution works well for you because you are using radio buttons. However there is a more general solution that I thought I should mention for future readers of this question.
You can change your DataTemplate to use plain "{Binding}"
Then in code you don't have to recreate a full DataTemplate. All you have to do is recreate this:
which is easy:
This is particularly convenient if you have many properties, even in your radio button example.
只需让自己变得简单并使用两个文本块并隐藏其中之一即可。
XAML:
隐藏代码:
Just make it simple for yourself and use two textblocks and hide one of them.
XAML:
Code behind:
您还可以使用值转换器来选择数据对象的任何属性。您将需要绑定到整个对象而不是单个属性。如果您的数据对象实现了 INotifyPropertyChanged,那么此解决方案将不适合您。
背后的XAML
代码:
You can also use a value converter to pick any property of your data object. You will need to bind to the whole object instead of individual properties. If your data object implements INotifyPropertyChanged then this solution will not work for you.
XAML
code behind: