我有一个绑定到itemssource集合中的属性的textblock。我想在同一个文本块中从那个类中显示两个属性,但看起来每次只能执行一个绑定。
我现在有这个:
Text="{Binding Title}"
但我想附加另一个属性,所以理论上是:
Text="{Binding Title - Author}"
输出像“莎士比亚-罗密欧和朱丽叶”。我试过添加逗号、另一个绑定和其他东西,但它们都会导致抛出异常(例如,元素textblock上的未知属性文本)。
两个属性都来自同一个类,因此我不需要有两个数据源。
最佳答案
不幸的是,Silverlight缺少了WPF能够处理的一些片段。我可能会使用一个值转换器,可以通过包含标题和作者的类来格式化文本。
代码如下:
public class TitleAuthorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is Book)) throw new NotSupportedException();
Book b = value as Book;
return b.Title + " - " + b.Author;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
}
一些xaml:
<Grid x:Name="LayoutRoot" Background="White">
<Grid.Resources>
<local:Book Title="Some Book" Author="Some Author" x:Key="MyBook"/>
<local:TitleAuthorConverter x:Key="Converter"/>
</Grid.Resources>
<TextBlock DataContext="{StaticResource MyBook}" Text="{Binding Converter={StaticResource Converter}}"/>
</Grid>
这样做的缺点是,如果属性发生更改(即实现了inotifypropertychanged),则无法更新文本,因为字段已绑定到类。
如问题注释中所建议的,您还可以创建第三个属性来组合它们。这将避免使用多绑定或值转换器。
关于c# - 将文本块绑定(bind)到两个属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6361657/