ListView项中的TextBlock文本绑定

本文关键字:文本 绑定 TextBlock ListView | 更新日期: 2023-09-27 18:25:19

当ListView中的选择发生更改时,如何更改TextBlock的Text
我不想手动执行此操作
ListView的所有项都是LogEntry的(类)。。。我可以在TextBlock的Text属性中使用Binding来获取所选项目的特定属性吗?

ListView项中的TextBlock文本绑定

是的,事实上有多种解决方案,我给你的答案最像"WPF",但imo也是最不灵活的。

首先,您需要设置IsSynchronizedWithCurrentItem="True"属性

现在,如果您选择了一个项目,绑定的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)