【发布时间】:2021-01-17 11:18:40
【问题描述】:
我有一个 DataTemplate 假设可以给我这种输出:
使用此代码时:
<DataTemplate x:DataType="data:MenuItem" x:Key="MenuItemTemplate">
<StackPanel>
<Viewbox Margin="10 10 10 2">
<TextBlock FontFamily="Segoe MDL2 Assets" Text="{x:Bind Icon}" />
</Viewbox>
<TextBlock HorizontalAlignment="Center" Text="{x:Bind Name}" />
</StackPanel>
</DataTemplate>
但是...我没有得到图标:
我认为我的绑定有问题,但我不知道是什么。
菜单项模型是这样的:
public class MenuItem
{
public MenuItem(string name, string icon)
{
Name = name;
Icon = $"&#x{icon};";
}
public string Name { get; set; }
public string Icon { get; set; }
}
如果我只是提供纯文本的图标,像这样:
<DataTemplate x:DataType="data:MenuItem" x:Key="MenuItemTemplate">
<StackPanel>
<Viewbox Margin="10 10 10 2">
<TextBlock FontFamily="Segoe MDL2 Assets" Text="" />
</Viewbox>
<TextBlock HorizontalAlignment="Center" Text="{x:Bind Name}" />
</StackPanel>
</DataTemplate>
图标显示正确,但使用绑定时不显示。
你能帮我理解我的方法有什么问题吗?
编辑:添加完整代码示例
public sealed partial class MainPage : Page
{
private ObservableCollection<MenuItem> MenuItems;
public MainPage()
{
this.InitializeComponent();
MenuItems = new ObservableCollection<MenuItem>(new List<MenuItem>
{
new MenuItem("Home","E913"),
new MenuItem("Volume","EC3F"),
new MenuItem("Scrap","E74C"),
new MenuItem("Report","ED25"),
});
}
}
public class MenuItem
{
public MenuItem(string name, string icon)
{
Name = name;
Icon = $"&#x{icon};";
}
public string Name { get; set; }
public string Icon { get; set; }
}
和 xalm 代码:
<Page.Resources>
<DataTemplate x:DataType="data:MenuItem" x:Key="MenuItemTemplate">
<StackPanel>
<Viewbox Margin="10 10 10 2">
<TextBlock FontFamily="Segoe MDL2 Assets" Text="{x:Bind Icon}" />
</Viewbox>
<TextBlock HorizontalAlignment="Center" Text="{x:Bind Name}" />
</StackPanel>
</DataTemplate>
</Page.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" ItemsSource="{x:Bind MenuItems}"
ItemTemplate="{StaticResource MenuItemTemplate}" />
</Grid>
【问题讨论】: