I have a Textblock that is bound to a property in the ItemsSource collection. I'd like to display two properties from that class in the same textblock, but it seems I can only perform one binding at a time. I currently have this:
Text="{Binding Title}"
but I want I want to append another property, so in theory it would be:
Text="{Binding Title - Author}"
with the output looking like "Shakespeare - Romeo and Juliet". I've tried adding a comma, another binding and other things, but they all result in an exception being thrown (e.g. Unknown attribute Text on element TextBlock).
Both properties comes from the same class, so I won't need to have two data sources.
Use this one.. It will work Perfectly.
<TextBlock>
<Run Text="{Binding Title}"></Run>
<Run Text=":"></Run>
<Run Text="{Binding Author}"></Run>
</TextBlock>
the output will be like this,
OOPS:Balagurusamy
Unfortunately silverlight is missing a few pieces that WPF has that can handle this. I would probably go the route of using a value converter that you can pass the class that contains the Title and Author to format the text.
Here's the code:
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; }
}
And some 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>
The downside to this way is that you won't get the text to update if the properties change (ie you implement INotifyPropertyChanged) since the field is bound to the class.
As suggested in the comments on the question, you could also create a third property that combines them. This would get around having to use multibindings or value converters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With