gpt4 book ai didi

c# - WPF DataTemplate 方法与参数绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 16:30:11 27 4
gpt4 key购买 nike

我有一个用于 ListBox 的自定义 ItemTemplate,我需要将 TextBlock“绑定(bind)”到一些特殊的方法/属性。

我的 ListBox 源是一个 ObservableCollection<SearchResultItem> . SearchResultItem包含一些属性。

文本需要根据另一个对象的值进行更改。例如,如果此对象等于“foo”,我需要文本值来调用方法 GetProperty("foo")SearchResultItem 上以获得正确的值。

这是一个代码示例:

<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"];如果有帮助。

最佳答案

好的,因为您的属性永远不会改变,这里有一个解决方案。您可以通过 SearchResultItem 类的另一个属性来执行此操作:

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

然后只需将您的文本框绑定(bind)到此属性:

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

关于c# - WPF DataTemplate 方法与参数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11103580/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com