views:

50

answers:

1

I have a bunch of textblocks in an itemscontrol... I need to know how can I underline the text in the textblock based on whether the text is available in a list in the data model..

Sounds very simple to me...but I have been googling since the past 8 hrs...

Can I use datatriggers and valueconverters for this purpose? If yes, then how can I execute the method which lies in the viewModel (the method which helps me to check whther a given a text exists in the data model list)...

Even if I go for conditional templating....how do I access the list which lies in my model (the viewmodel can fetch it...but then how do i access the viewmodel?)..

This should be a fairly easy thing to do...Am I really missing something very simple here?? :)

I am following the MVVM pattern for my application..

+1  A: 

One way is to use a multivalueconverter which is a class that implements IMultiValueConverter. A multivalueconverter allows you to bind to several values which means that you can get a reference to both your viewmodel and the text of your TextBlock in your valueconverter.

Assuming that your viewmodel has a method called GetIsUnderlined that returns true or false indicating whether or not the text should be underlined your valueconverter can be implemented along these lines:

class UnderlineValueConverter : IMultiValueConverter
{
    #region IMultiValueConverter Members

    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var viewmodel = values[0] as Window1ViewModel;
        var text = values[1] as string;
        return viewmodel.GetIsUnderlined(text) ? TextDecorations.Underline : null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter,     System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

You can use this valueconverter in the following way for a TextBlock:

<Grid x:Name="grid1" >
    <Grid.Resources>
        <local:UnderlineValueConverter x:Key="underlineValueConverter" />
    </Grid.Resources>

    <TextBlock Text="Blahblah">
        <TextBlock.TextDecorations>
            <MultiBinding Converter="{StaticResource underlineValueConverter}">
                <Binding /> <!-- Pass in the DataContext (the viewmodel) as the first parameter -->
                <Binding Path="Text" RelativeSource="{RelativeSource Mode=Self}" /> <!-- Pass in the text of the TextBlock as the second parameter -->
            </MultiBinding>
        </TextBlock.TextDecorations>
    </TextBlock>
</Grid>
Jakob Christensen