Silverlight-绑定图像资源到矩形填充
-
02-10-2019 - |
题
Blend 4告诉我这是无效的标记,它并没有告诉我为什么:
<ImageBrush Stretch="Fill" ImageSource="{Binding Avatar, Mode=OneWay}"/>
我正在从Twitter提要中提取数据,保存到ImageSource,然后将其绑定到ImageBrush(如下所示),以用作矩形的填充。这是更多上下文:
<Rectangle x:Name="Avatar" RadiusY="9" RadiusX="9" Width="45" Height="45" VerticalAlignment="Center" HorizontalAlignment="Center" >
<Rectangle.Fill>
<ImageBrush Stretch="Fill" ImageSource="{Binding Avatar, Mode=OneWay}"/>
</Rectangle.Fill>
</Rectangle>
我正在使用Silverlight UserControl内部的此内部,该银光在Silverlight应用程序内使用。关于问题可能发生的任何想法?
解决方案
绑定不能应用于ImageBrush的ImageSource,或者似乎是如此。我遇到了类似的问题并寻找替代方案。
其他提示
您无法绑定到ImageBrush的图像资源,但是您可以绑定到形状的填充属性。因此,以下作品:
<Rectangle Name="myRect" Fill="{Binding Avatar}"/>
有这样的课程:
public class AvatarClass
{
public ImageBrush Avatar { get; set; }
}
和这样的代码:
myRect.DataContext = new AvatarClass{
Avatar = new ImageBrush {
ImageSource = new BitmapImage(avatarUri)}};
在这里您走:WPF / Silverlight
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:convertor="clr-namespace:WpfApplication1.Converters"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<convertor:RectangleImageFillConvertor x:Key="RectangleImageFillConvertor" />
</Window.Resources>
<Grid>
<Rectangle HorizontalAlignment="Center"
RadiusX="10"
RadiusY="10"
Width="200"
Height="200"
Fill="{Binding ImageUrl, Converter={StaticResource RectangleImageFillConvertor}}"/>
</Grid>
</Window>
blockquote
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public string ImageUrl { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
ImageUrl = "http://www.deargrumpycat.com/wp-content/uploads/2013/02/Grumpy-Cat1.jpg";
}
}
}
BlockQuote BlockQuote
namespace WpfApplication1.Converters
{
public class RectangleImageFillConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
return new ImageBrush(new BitmapImage(new Uri(value as string, UriKind.RelativeOrAbsolute)));
//if silverlight
// return new ImageBrush{ ImageSource = new BitmapImage(new Uri(value as string, UriKind.RelativeOrAbsolute))};
}
catch
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
不隶属于 StackOverflow