在网格内部,我想显示一个基于int属性DocumentType的图标。
这个工作正常(它确实在网格单元中显示int属性DocumentType,例如1,2,3):
<TextBlock Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" MaxHeight="45" MaxWidth="45" Text="{Binding DocumentType}"/>
此根本不起作用(它不会在网格单元格中显示任何内容):
<Path Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" MaxHeight="45" MaxWidth="45" Stretch="Uniform" Data="{Binding DocumentType, Converter={StaticResource DocumentTypeIcon}}"/>
以下是资源:
<Application.Resources>
<ResourceDictionary>
<Path x:Key="Icon0" Fill="Black" Data="M12.126984,0L19.872009,0 19.872009,12.128 32,12.128 32,19.872999 19.872009,19.872999 19.872009,31.999 12.126984,31.999 12.126984,19.872999 0,19.872999 0,12.128 12.126984,12.128z" />
<Path x:Key="Icon1" Fill="Blue" Data="M12.126984,0L19.872009,0 19.872009,12.128 32,12.128 32,19.872999 19.872009,19.872999 19.872009,31.999 12.126984,31.999 12.126984,19.872999 0,19.872999 0,12.128 12.126984,12.128z" />
<Path x:Key="Icon2" Fill="Blue" Data="M12.126984,0L19.872009,0 19.872009,12.128 32,12.128 32,19.872999 19.872009,19.872999 19.872009,31.999 12.126984,31.999 12.126984,19.872999 0,19.872999 0,12.128 12.126984,12.128z" />
<Path x:Key="Icon3" Fill="Red" Data="M12.126984,0L19.872009,0 19.872009,12.128 32,12.128 32,19.872999 19.872009,19.872999 19.872009,31.999 12.126984,31.999 12.126984,19.872999 0,19.872999 0,12.128 12.126984,12.128z" />
</ResourceDictionary>
</Application.Resources>
这是转换器:
public class DocumentTypeToIconConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
var iDocumentType = Int32.Parse( (string) value);
switch (iDocumentType)
{
case 1:
return Application.Current.FindResource("Icon1");
case 2:
return Application.Current.FindResource("Icon2");
case 3:
return Application.Current.FindResource("Icon3");
default:
return Application.Current.FindResource("Icon0");
}
}
return Application.Current.FindResource("Icon0");
}
…
}
在我看来,这是一个非常常见的用例。我尽力寻找解决方案。我对不同的建议持开放态度,虽然我理解,作为“向量”或“路径”(如图所示)提供的图标比以png提供的图标更好地缩放,这是我更喜欢“路径”图标的原因。为了对问题提出一些背景,我是XAML和C#的新手。 感谢。
答案 0 :(得分:2)
为Geometry类型的Data属性创建绑定。 Converter返回Path对象。发生类型不匹配。
使用其他控件显示路径
Native
从资源中重用<ContentControl Grid.Row="0" Grid.Column="0" Grid.RowSpan="2"
MaxHeight="45" MaxWidth="45"
Content="{Binding DocumentType, Converter={StaticResource DocumentTypeIcon}}"/>
个对象存在问题(类似案例Content of a Button Style appears only in one Button instance)
更好地将Geometry声明为资源
Path
并使用不同的转换器为每种文档类型返回Brush:
<Geometry x:Key="Ico" >
M12.126984,0L19.872009,0 19.872009,12.128 32,12.128 32,19.872999 19.872009,19.872999 19.872009,31.999 12.126984,31.999 12.126984,19.872999 0,19.872999 0,12.128 12.126984,12.128z
</Geometry>
<Path Grid.Row="0" Grid.Column="0" Grid.RowSpan="2"
MaxHeight="45" MaxWidth="45" Stretch="Uniform"
Fill="{Binding DocumentType, Converter={StaticResource DocumentTypeColor}}"
Data="{StaticResource Ico}"/>