2012-06-19 61 views
2

我有一个ListBox的自定义ItemTemplate,我需要将一个TextBlock绑定到某些特殊的方法/属性。WPF DataTemplate方法绑定参数

我的列表框源是一个ObservableCollection<SearchResultItem>SearchResultItem包含一些属性。

该文本需要根据另一个对象的值进行更改。 E.G如果此对象等于“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方法。

- 这就是说,如果有帮助,“富”值来自ConfigurationManager.AppSettings["propertyName"];

+0

您是否尝试过使用转换器? – benjer3

+0

我见过一些使用转换器的代码示例,但我不知道如何通过这种方式访问​​“foo”对象的值。 –

+0

你说你有一个自定义列表框的DataTemplate,但我想你想说的是,你有一个ListBox的自定义ItemTemplate ...我是否正确? – Thelonias

回答

0

好的,因为你的属性永不改变,这里有一个解决方案。您可以在SearchResultItem类通过另一个属性做到这一点:

public string MyTextBinding 
{ 
    get 
    { 
     return myDictionary.ContainsKey("foo") ? return myDictionary["foo"] : return "myDictionary doesn't contain foo"; 
    } 
} 

然后,只需你的文本框绑定到这个属性:

<DataTemplate>  
    <Label Margin="2,2,2,0" Grid.Row="0" Grid.Column="2" Content="{Binding Path=Date}" HorizontalAlignment="Right" HorizontalContentAlignment="Right" /> 
    <TextBlock Margin="2,2,2,0" TextTrimming="CharacterEllipsis" Grid.Row="0" Grid.Column="1" Text="{Binding Path=MyTextBinding, Mode=OneWay}" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="Black"/> 
</DataTemplate> 
+0

我不能这样做,因为SearchResultItem来自外部库,它不知道“foo”。 –

+0

你可以为它编写一个包含SearchResultItem的包装器,并将你的ObservableCollection变成这些包装器的集合 – Thelonias

+0

我在想那个,但我不太喜欢这个包装的想法。我正在考虑一个绑定/ xaml解决方案。事实上,如果没有其他解决方案提出,我会继续并包装我的物品。 –

0

只需使用一个IValueConverter,需要一个SearchResultItem和返回预期的文本

<TextBlock Margin="2,2,2,0" TextTrimming="CharacterEllipsis" 
      Grid.Row="0" Grid.Column="1" 
      Text="{Binding Path=., 
       Converter={StaticResource PropertyValueFromSearchResultItemConverter}, 
       ConverterParameter=Foo}" 
      HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="Black"/> 
+0

我会试试这个,谢谢! –