tags:

views:

950

answers:

2

Hi.

I have a TextBlock that I want to display a user name, and email like this:

Firstname Lastname (Email)

However, I don't want to put the (Email) part in if the user doesn't have an email on file. I would also like to italicize the email. Normally, I would use a TextBlock and add Runs in for the various parts of the text, but I can't find a way to dynamically change a TextBlock's inlines from XAML.

I've tried this:

<TextBlock.Triggers>
<DataTrigger Binding="{Binding Path=HasEmail}" Value="True">

  <Setter Property="Inlines" TargetName="contactTagNameEmailTextBlock">
    <Setter.Value>
     <Run Text="{Binding Path=Firstname}" />
     <Run Text="{Binding Path=Lastname}" />
     <Run Text="(" />
     <Run Text="{Binding Path=Email}" />
     <Run Text=")" />
  </Setter.Value>

</Setter>
</DataTrigger>
</TextBlock.Triggers>

But VS complains that the value is set more than once (due to the multiple Run's). How can I get around this? Alternatively, it would be really convenient if I could set a binding on a whole FrameworkElement. For example, if I could just put a placeholder in my Grid where I want to put a custom control I construct in code behind on this bound object, that would be the best.

Thanks.

+2  A: 

Something like that should work :

<Window.Resources>
    <BooleanToVisibility x:Key="visibilityConverter"/>
</Window.Resources>

...

<TextBlock>
    <Run Text="{Binding Path=Firstname}" />
    <Run Text="{Binding Path=Lastname}" />
    <TextBlock Visibility="{Binding HasEmail, Converter={StaticResource visibilityConverter}}">
        <Run Text="(" />
        <Run Text="{Binding Path=Email}" />
        <Run Text=")" />
    </TextBlock>
</TextBlock>
Thomas Levesque
This works, thanks! WPF is definitely a different way of doing things.
Max
+1  A: 

Look into Multibinding and StringFormat

<TextBlock>
  <TextBlock.Text>
    <MultiBinding StringFormat="{}{0}, {1}">
      <Binding Path="LastName" />
      <Binding Path="FirstName" />
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>

You should be able to hide the () if email isn't there.

karl.r
I don't know how to hide part of a format string if one of the parameters is empty. Is it even possible?
Max