一种可能性是使用ValueConverter。它非常灵活、解耦并且有助于让 xaml 变得简单。这里是这样一个值转换器的代码:
public class ImageCountValueConverter : IValueConverter{
public string ImagePath {
get;
set;
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
if(null == value){
return Enumerable.Empty<string>();
} else if (value is int) {
List<string> list = new List<string>();
int v = (int)value;
for (int i = 0; i < v; i++) {
if (parameter is string) {
list.Add((string)parameter);
} else {
list.Add(ImagePath);
}
}
return list;
} else {
Type t = value.GetType();
throw new NotSupportedException("The \"" + t.Name+ "\" type is not supported");
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
标记看起来像这样:
<StackPanel>
<ItemsControl ItemsSource="{Binding Yellow,Converter={StaticResource ImageCount_ValueConverter},ConverterParameter=/image/yellow.png}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}" Stretch="None"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding Red,Converter={StaticResource ImageCount_ValueConverter},ConverterParameter=/image/red.png}" >
...
声明类似于:
<Window.Resources>
<local:ImageCountValueConverter x:Key="ImageCount_ValueConverter" ImagePath="/image/sampleImage.png"/>
</Window.Resources>
选项
根据您的要求,您还可以扩展或更改它以使用 ImageSource 而不是字符串,甚至提供List<Brush> 作为输出,然后在通过绑定设置画笔的 DataTemplate 中使用形状。