wpf 列表框将单个项目更改为粗体
题
我希望根据我放入列表框中的对象的属性,将某些项目设为粗体。
我认为你可以通过更改模板来做到这一点,但似乎找不到示例。
谢谢!
解决方案
您可以做到这一点更简单地比,如果你使用一个转换器(IntToFontWeightConverter,例如)。
设置项模板:
<DataTemplate x:Key="BoldTemplate">
<TextBlock
FontWeight="{Binding Path=Position, Converter={StaticResource IntToFontWeightConverter}}"
Text="{Binding Path=Name}"
/>
</DataTemplate>
其中name是要显示什么内容和位置是你立足黑体/正常你的财产。
创建您的转换器(取决于你的基础上大胆的属性的类型)。
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
}
其他提示
您可以使用 DataTriggers 来完成此操作。有关使用 DataTrigger 的简单示例,您可以查看 http://manicprogrammer.com/cs/blogs/willeke/archive/2007/04/25/datatriggers-are-very-cool.aspx
这是使用 ListView 的示例,但同样的情况也适用于 Listbox。
<ListView x:Name="Notes" Margin="4,4,4,4"
ItemsSource="{Binding Path=CurrentCustomer.CustomerNotes}"
ItemTemplate="{DynamicResource CustomerNotesDataTemplate}"
Style="{DynamicResource ListViewStyle1}" />
然后 ItemTemplate 位于我的窗口资源中:
<DataTemplate x:Key="CustomerNotesDataTemplate">
<Grid MinWidth="400" Style="{DynamicResource NotesRowTriggers}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="74"/>
<ColumnDefinition Width="400"/>
<ColumnDefinition Width="125"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top" Text="{Binding Path=NoteDate, Converter={StaticResource ShortDateConverter}}" Margin="0,0,4,0" />
<TextBlock Text="{Binding Path=FreeNote}" Grid.Column="1" HorizontalAlignment="Stretch" Margin="4,0,0,0" Grid.ColumnSpan="1" TextWrapping="Wrap" />
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Top" Text="{Binding Path=NoteUser}" Grid.Column="2" Width="110" d:LayoutOverrides="Width" Margin="4,0,0,0" Grid.ColumnSpan="1" />
<CheckBox HorizontalAlignment="Left" IsChecked="{Binding Path=Highlight}" VerticalAlignment="Top" Content="Important" Grid.Column="3" Margin="4,0,4,0"/>
<CheckBox HorizontalAlignment="Left" IsChecked="{Binding Path=Important}" VerticalAlignment="Top" Content="Alert" Grid.Column="4" Margin="4,0,4,0"/>
</Grid>
</DataTemplate>
最后,带有 DataTriggers 的样式也在我的窗口资源中。
<Style x:Key="NotesRowTriggers" TargetType="{x:Type Grid}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Important}" Value="True">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="Red" Opacity="0.3" />
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Path=Highlight}" Value="True">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="Red" Opacity="0.6" />
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
我的示例可能比需要的要详细得多,但我只是直接从我的一个应用程序中提取它。
不隶属于 StackOverflow