我正在自学一些 .NET 编程,目前正在尝试在 WPF 中构建标签云控件。目的是在一个窗口上有 2 个列表框,第一个列表框显示“联系人列表”列表,第二个列表框显示与联系人列表关联的“标签”(或标签)。对于标签,目标是使用 IValueConverter 将字体大小绑定到 itemCount,因此如果我有一个特定标签在我的集合中出现多次,它将在标签列表框中以更大的字体显示。此外,我正在从 DB2 数据库填充我的控件。
所以我已经在正确的列表框中显示联系人列表和标签,我只是在绑定时遇到了一些问题。我正在使用从教程中获取的转换器类,并且想知道是否有人可以帮助我完成这项工作。非常感谢 - 本
特性
public class Label
{
public int LabelID { get; set; }
public string LabelName { get; set; }
}
联系人列表类
public class ContactList
{
public string ContactListName { get; set; }
public List<Label> Labels { get; set; }
}
转换器
public class CountToFontSizeConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
const int minFontSize = 6;
const int maxFontSize = 38;
const int increment = 3;
int count = (int)value;
return ((minFontSize + count + increment) < maxFontSize) ?
(minFontSize + count + increment) :
maxFontSize;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
窗口加载事件
private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
//TODO: Add event handler implementation here.
ListCollectionView lcv = new ListCollectionView(myLabels);
lcv.GroupDescriptions.Add(new PropertyGroupDescription("LabelName"));
tagsList.ItemsSource = lcv.Groups;
}
XAML
<Window.Resources>
<local:CountToFontSizeConverter x:Key="CountToFontSizeConverter"/>
<Style x:Key="tagsStyle" TargetType="{x:Type ListBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}">
<Grid>
<Border x:Name="Border"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"/>
<WrapPanel Orientation="Horizontal"
Margin="2"
IsItemsHost="true"
Background="#FFFCF6F6"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<DataTemplate x:Key="ContactsTemplate">
<WrapPanel>
<TextBlock TextWrapping="Wrap"
Text="{Binding ContactListName, Mode=Default}"/>
</WrapPanel>
</DataTemplate>
<DataTemplate x:Key="TagsTemplate">
<WrapPanel>
<TextBlock Text="{Binding LabelName, Mode=Default}"
TextWrapping="Wrap"
FontSize="{Binding ItemCount,
Converter={StaticResource CountToFontSizeConverter},
Mode=Default}"
Foreground="#FF0D0AF7"/>
</WrapPanel>
</DataTemplate>
</Window.Resources>
<Grid x:Name="LayoutRoot" Background="#FFCBD5E6">
<ListBox x:Name="contactsList"
SelectionMode="Multiple"
Margin="7,8,0,7"
ItemsSource="{Binding ContactLists, Mode=Default}"
ItemTemplate="{DynamicResource ContactsTemplate}"
HorizontalAlignment="Left"
Width="254"/>
<ListBox x:Name="tagsList"
Margin="293,8,8,8"
ItemsSource="{Binding Labels, Mode=Default}"
ItemTemplate="{StaticResource TagsTemplate}"
Style="{StaticResource tagsStyle}" />
</Grid>