【发布时间】:2012-06-21 15:31:06
【问题描述】:
我有一个用于 ListBox 的自定义 ItemTemplate,我需要将 TextBlock“绑定”到一些特殊的方法/属性。
我的列表框源是ObservableCollection<SearchResultItem>。 SearchResultItem 包含一些属性。
文本需要根据另一个对象的值进行更改。例如,如果此对象等于“foo”,我需要文本值来调用 SearchResultItem 上的方法 GetProperty("foo") 以获得正确的值。
这是一个代码示例:
<DataTemplate>
..
//Here is a Label bound to the Date Property of the SearchResultItem
<Label Margin="2,2,2,0" Grid.Row="0" Grid.Column="2" Content="{Binding Path=Date}" HorizontalAlignment="Right" HorizontalContentAlignment="Right" />
//Here is the textblock that needs to call the method with the parameter based on the value of the other object.
<TextBlock Margin="2,2,2,0" TextTrimming="CharacterEllipsis" Grid.Row="0" Grid.Column="1" Text="I need some help there" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="Black"/>
..
</DataTemplate>
您对如何做到这一点或更好的方法有任何想法吗?
编辑:
-假设SearchResultItem 来自外部库并且只公开GetProperty 方法。
-假设“foo”值来自ConfigurationManager.AppSettings["propertyName"];,如果有帮助的话。
【问题讨论】:
-
你试过用转换器吗?
-
我见过一些使用转换器的代码示例,但我不知道如何以这种方式访问“foo”对象值。
-
你说你有一个用于自定义 ListBox 的 DataTemplate,但我想你想说的是你有一个用于 ListBox 的自定义 ItemTemplate ......我说得对吗?
-
@Ryan 你是对的,我编辑了 OP
-
@DannyWillem,好的,一旦 SearchResultItem 添加到集合中,属性的值会改变吗?
标签: c# wpf binding datatemplate