【发布时间】:2012-02-22 09:33:16
【问题描述】:
当我的 ListView 中的选择发生变化时,如何更改 TextBlock 的文本?
我不想手动执行此操作...
ListView 的所有 Item 都是 LogEntry 的(类)...我可以在 TextBlock 的 Text-Attribute 中使用 Binding 来获取所选 Item 的特定属性吗?
【问题讨论】:
当我的 ListView 中的选择发生变化时,如何更改 TextBlock 的文本?
我不想手动执行此操作...
ListView 的所有 Item 都是 LogEntry 的(类)...我可以在 TextBlock 的 Text-Attribute 中使用 Binding 来获取所选 Item 的特定属性吗?
【问题讨论】:
是的,实际上有多种解决方案,我给你的答案最像“WPF”,但 imo 也是最不灵活的。
首先你需要设置IsSynchronizedWithCurrentItem="True"property
现在,如果您选择一个项目,绑定的CollectionView 会将项目设置为 CurrentItem。
现在您的 TextBox/Block 可以通过使用“/”的特殊绑定语法绑定到此特定项目。 例如:
<TextBlock Text="{Binding LogEntries/}"/>
当然,您也可以通过绑定从当前项目中获取特定属性
<TextBlock Text="{Binding LogEntries/WarningMessage}"/>
希望对您有所帮助。
【讨论】:
假设你有一个这样的列表视图:
<ListView ItemSource="{Binding LogEntries}" Name="logs" IsSynchronizedWithCurrentItem="True">
</ListView>
<ContentControl Content="{Binding ElementName=logs, Path=SelectedItem}" ContentTemplate="{StaticResource logTemplate}"/>
现在您需要在资源中提供该 logTemplate。
<UserControl.Resources>
<DataTemplate DataType="{x:Type local:LogEntry}">
<TextBlock Text="{Binding Path=LogText}"/> <-- This is a Property-Binding of your custom class
</DataTemplate>
</UserControl.Resources>
最后缺少的是为本地类 LogEntry 提供命名空间。如果你使用像 Resharper 这样很棒的工具,它会为你插入命名空间。否则,这里是一个示例声明:
<UserControl xmlns:local="clr-namespace:My.App.Namespace.LogEntry;assembly=My.App"
... (rest of namespace declarations)
【讨论】: