开发者

WPF : Conditional templating of textblock

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 mode开发者_如何学Pythonl (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..


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜