简而言之,我想在 GridView 中创建一组图标,用户可以从中选择一个图标来更改其配置文件图标。
我想我可以通过在ResourceDictionary
上声明我需要的图标来实现这一目标
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:iconPacks="using:MahApps.Metro.IconPacks">
<iconPacks:PackIconMaterial x:Key="IconCarrot" Kind="Carrot"/>
<FontIcon x:Key="IconRobot" FontFamily="Segoe MDL2 Assets" Glyph=""/>
<!--As can we see, the icons are of different types-->
</ResourceDictionary>
将其添加到App.xaml
<Application.Resources ...>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ResourceDictionaries/MyIcons.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
此外,我创建了一个类来实例化具有两个属性的IconObject
:实际的 Icon 和我想像工具提示文本一样使用的字符串
public class IconObject
{
// I really don't know what type I need to use here
public object DisplayedIcon { get; set; }
// Tooltip
public string DisplayedToolTip { get; set; }
// Contructor
public IconObject(object theIcon, string theTooltip)
{
DisplayedIcon = theIcon;
DisplayedToolTip = theTooltip;
}
}
因此,在代码中,我有一个想要填充的ObservableCollection<IconObject>
private void PopulateTheObservableCollection()
{
IconObjects.Add(new IconObject(Application.Current.Resources["IconCarrot"], "Carrot"));
}
最后,我正在尝试绑定网格视图
<GridView ItemsSource="{x:Bind IconObjects}">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid MaximumRowsOrColumns="6" Orientation="Horizontal" ItemHeight="50" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<DataTemplate x:DataType="local:IconObject" >
<Viewbox Child="{x:Bind DisplayedIcon}" ToolTipService.ToolTip="{x:Bind DisplayedToolTip}"/>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
但是抛出一个错误(我可以看到为什么,但我不知道如何修复它(。
这里的问题是
- 这是执行此操作的好方法(使网格视图填充了用户可以选择的图标,然后使用所选图标(?
- 我需要使用什么类型的属性来存储图标?
- 你有什么建议吗?
(感谢您的时间和阅读所有这些内容(
我需要使用什么类型的属性来存储图标?
根据您的代码,您希望将图标添加到 Viewbox,子程序的类型是 UIElement,因此您可以将 DisplayIcon 属性设置为 UIElement 类型或保留对象类型并使用转换器方法对其进行转换。此外,如果要将图标添加到视图框中,则需要先在资源字典中删除它,然后将其添加到视图框中,元素的实例不能在 XAML 树中多次出现。例如:
型:
public class IconObject
{
// I really don't know what type I need to use here
public UIElement DisplayedIcon { get; set; }
// Tooltip
public string DisplayedToolTip { get; set; }
// Contructor
public IconObject(UIElement theIcon, string theTooltip)
{
DisplayedIcon = theIcon;
DisplayedToolTip = theTooltip;
}
}
.xaml.cs:
更新:
private void PopulateTheObservableCollection()
{
ResourceDictionary dic = Application.Current.Resources.MergedDictionaries[0];
UIElement iconElement = dic["IconCarrot"] as UIElement;
dic.Remove("IconCarrot");
IconObjects.Add(new IconObject(iconElement, "Carrot"));
}
这是这样做的好方法
您可以尝试使用DataTemplateSelector方法根据不同类型的图标创建不同的DataTemplate和模型。有关数据模板选择器的更多详细信息,可以参考此文档。