views:

210

answers:

1

I'm binding a collection of objects to a listbox in WPF, for simplicity we'll say the object i'm binding has 3 propertys: Name, URL, IsBold. What I want to do, is have it displayed different if the IsBold is set to true, again as an example I want to set the TextBlock that Name appears in, to be bold. Is something like this even possible? Can I use a different style or something if one of my properties is a certain value? (can I do anything like an if/else in XAML)? I really have no idea where to start with this.

Say I have this in my DataTemplate

<TextBlock Style="{StaticResource notBold}" Text="{Binding Path=Name}"></TextBlock>

And if the IsBold is set to true for that particular Item I would like it to be (notice the style changes from 'notBold' to 'isBold')

<TextBlock Style="{StaticResource isBold}" Text="{Binding Path=Name}"></TextBlock>

Or something similar. I guess the more general question. Is it possible to change the apperance of something based on an item that's databound? And if it's not possible, how would something like this be done? Thru the code-behind somehow?

Thanks

+3  A: 

What you'd normally do is write a DataTemplate for the objects in the list and then have a DataTrigger set the Fontweight of the TextBlock/TextBox based on the IsBold Property.

<DataTemplate DataType="DataItem">
    <TextBlock x:Name="tb" Text="{Binding Name}"/>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding IsBold}" Value="true">
            <Setter TargetName="tb" Property="FontWeight" Value="Bold" />
        </DataTrigger>
        <DataTrigger Binding="{Binding IsBold}" Value="false">
            <Setter TargetName="tb" Property="FontWeight" Value="Normal" />
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

You'd then set a list of DataItems to the ItemsSource property of your ComboBox (either by Databinding or directly in the codebehind myComboBox.ItemsSource=myDataItems). The rest is done by WPF for you.

bitbonk
I can't believe I looked around the web for hours without thinking of using a DataTrigger. I knew skimming over those chapters in that WPF book was going to get me. Thank you so much.
kyle