我正在尝试基于现有实现[下载源代码] 在 WPF 中构建标签云。我不完全理解实现,我的问题是,我不想将 FontSize 绑定到集合中的项目数,而是想将它绑定到类中包含的其他一些值。所以在这里的这一部分,
FontSize="{Binding Path=ItemCount, Converter={StaticResource CountToFontSizeConverter}}"
我想将 FontSize 绑定到其他东西。我怎么做?ItemCount 属于哪里?
谢谢
ItemCount
属于从该标签生成的集合视图内的组。
例如,如果我有一个清单
AABBBC
我将它们分组,我得到:
A 组:ItemCount = 2
B 组:ItemCount = 3
C 组:ItemCount = 1
标签云的全部意义在于绑定到该属性,因为您想可视化某个标签的使用频率。
要回复您的评论,基本设置应该是这样的:
<ItemsControl ItemsSource="{Binding Data}">
<ItemsControl.Resources>
<vc:CountToFontSizeConverter x:Key="CountToFontSizeConverter"/>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Margin="2"
FontSize="{Binding Count, Converter={StaticResource CountToFontSizeConverter}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我假设您的数据对象类公开了属性Name
,并且Count
为了确保随着数据对象类需要实现的计数的增加而改变大小INotifyPropertyChanged
,这就是它的全部内容。
public class Tag : INotifyPropertyChanged
{
private string _name = null;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
private int _count = 0;
public int Count
{
get { return _count; }
set
{
if (_count != value)
{
_count = value;
OnPropertyChanged("Count");
}
}
}
//...
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
ItemCount 是包含在要更改其 FontSize 的 WPF 对象的 DataContext 属性中的任何实例的属性。在层次结构树中,从后面的所有内容都FrameworkElement
继承“DataContext”属性。
使用“snoop”,您可以在运行时查看 WPF 应用程序的 UI 树,例如找出在任何给定时间存在于 DataContext 中的对象。