【问题标题】:TextBlock Text-Binding from ListView items来自 ListView 项的 TextBlock 文本绑定
【发布时间】:2012-02-22 09:33:16
【问题描述】:

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

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

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

    首先你需要设置IsSynchronizedWithCurrentItem="True"property

    现在,如果您选择一个项目,绑定的CollectionView 会将项目设置为 CurrentItem。

    现在您的 TextBox/Block 可以通过使用“/”的特殊绑定语法绑定到此特定项目。 例如:

    <TextBlock Text="{Binding LogEntries/}"/>
    

    当然,您也可以通过绑定从当前项目中获取特定属性

    <TextBlock Text="{Binding LogEntries/WarningMessage}"/>
    

    希望对您有所帮助。

    【讨论】:

    • 但是当 listView 的选择发生变化时,TextBox-Text 必须更新......所以我需要 listView 的特定项目和每个 TextBox 的 LogEntry-Item 的特定属性(DependencyProperty) ...
    • 别担心,确实如此。当您将集合绑定到 ItemsControl 时,WPF 不会直接绑定它,而是在控件和您的集合之间绑定 CollectionView。使用 IsSynchronizedWithCurrentItem,collectionview 将跟踪您选择的项目。绑定到您的集合,使绑定知道 CollectionView,因此每个控件绑定到您的集合,也可以访问当前项。
    • @LucaNateMahler 请记住接受答案,给予适当的信任。
    【解决方案2】:

    假设你有一个这样的列表视图:

    <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)
    

    【讨论】:

    • 是的,ItemsSource 是正确的。在内部,我使用 ObservableCollection 并且 LogEntry 是 DependencyObject 的子类...
    • 好的,看来您需要阅读有关 wpf 的文章或书籍,但要回答您的问题:内容控件可以显示任何类型的元素,并且当您给它一个内容模板时,它会设置样式根据那个模板。另一方面,DataTemplate 是一个(顾名思义)模板,适用于某种数据类型(在您的情况下为 LogEntry),并包含绑定到该类型属性的元素。关于这个主题有很多很好的初学者文章。谷歌是你的朋友。
    猜你喜欢
    • 2013-01-15
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2011-01-01
    • 1970-01-01
    • 2012-10-24
    相关资源
    最近更新 更多