Search code examples
wpftextlistboxtemplatesbold

wpf listbox change individual items to bold


I want some of the items to be bold depending on a property of an object i'm putting into the listbox.

I think you can do it with changing templates but can't seem to find an example.

Thanks!


Solution

  • You can do it more simply than that if you use a converter (IntToFontWeightConverter, for example).

    Set up an item template:

     <DataTemplate x:Key="BoldTemplate">
        <TextBlock
            FontWeight="{Binding Path=Position, Converter={StaticResource IntToFontWeightConverter}}"
            Text="{Binding Path=Name}" 
            />
    </DataTemplate>     
    

    where Name is what you want to display, and Position is your property that you are basing the bold / normal on.

    Create your converter (depending on the type of the property that you base the bold on).

    class IntToFontWeightConverter :IValueConverter 
    {
        #region IValueConverter Members
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if ((int)value == 1)
            {
                return FontWeights.Bold;
            }
    
            return FontWeights.Normal;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    
        #endregion
    }