我在ItemsControl的DataTemplate
中使用动态加载的图像作为我的网格元素的背景<ItemsControl Name="Category_Items" HorizontalContentAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Margin="10" Name="WrapPanel" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Cursor="Hand" Margin="4,0,4,8" Width="{Binding Converter={StaticResource PercentageConverter}, ElementName=WrapPanel, Path=ActualWidth, ConverterParameter='0,25'}"
Height="{Binding Converter={StaticResource PercentageConverter}, Path=ActualWidth, RelativeSource={RelativeSource Self},ConverterParameter='0,6'}">
<Grid.Background>
<ImageBrush ImageSource="{Binding Logo, Converter={StaticResource ImageConverter}}" />
</Grid.Background>
<TextBlock Text="{Binding Name}" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0,0,5"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
你可以看到我的网格元素宽度和高度属性由WrapPanel的实际宽度和它自己的高度决定。
我使用下面的转换器类来获取图像并从网上加载它。
public class ImageConverter : IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(value as string, UriKind.Absolute);
image.CacheOption = BitmapCacheOption.None;
image.EndInit();
return image;
}
public object ConvertBack(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
似乎工作正常。但是图像在加载时是不可见的。拖动或调整主窗口大小后,将显示图像。
更新 这是UI,我尝试构建。
我尝试在加载后刷新用户控件。但它没有帮助。
任何想法?
答案 0 :(得分:0)
<ItemsControl Name="Category_Items" HorizontalContentAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Margin="10" Name="WrapPanel" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid ClipToBounds="True" Cursor="Hand" Margin="4,0,4,8" Width="{Binding Converter={StaticResource PercentageConverter}, ElementName=WrapPanel, Path=ActualWidth, ConverterParameter='0,333'}"
Height="{Binding Converter={StaticResource PercentageConverter}, Path=ActualWidth, RelativeSource={RelativeSource Self},ConverterParameter='0,6'}">
<Image Source="{Binding Logo, IsAsync=True}" Stretch="UniformToFill" />
<lib:TextPath Text="{Binding Name}" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0,0,5" FontSize="22" Fill="White" Stroke="Black" FontWeight="Bold"/>
<Grid.InputBindings>
<MouseBinding MouseAction="LeftClick" Command="{Binding GetCompanies}" CommandParameter="{Binding Id}"></MouseBinding>
</Grid.InputBindings>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>