我对此非常陌生。我正在尝试在WPF中创建一个自定义控件,它将在其下方显示图像和一段文本。我从url下载图像作为BitmapImage类型。我有一个在我的UI上测试它正确下载它是。它下载并显示在,但在自定义控件中,Icon依赖属性只显示URL(我假设它是它看到的ToString())。
这就是LEFT上功能框的外观,我用它来确认图像是否正确进入,以及右侧出现故障的GameIconControl:
http://i.imgur.com/heLcUMc.png
以下是控件的Generic.xaml
<Style TargetType="{x:Type assets:GameIconControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type assets:GameIconControl}">
<Border Background="Transparent"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel HorizontalAlignment="Center"
VerticalAlignment="Center"
Orientation="Vertical">
<ContentPresenter Height="Auto"
Margin="3"
ContentSource="Icon"
HorizontalAlignment="Center"/>
<ContentPresenter Height="Auto"
Margin="3"
ContentSource="GameName"
HorizontalAlignment="Center"/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
这是GameIconControl.cs中的C#
public class GameIconControl : Control
{
static GameIconControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(GameIconControl), new FrameworkPropertyMetadata(typeof(GameIconControl)));
}
public GameIconControl(){}
public GameIconControl(string name, BitmapImage icon)
{
Icon = icon;
GameName = name;
}
public const string IconPropertyName = "Icon";
public const string GameNamePropertyName = "GameName";
public string GameName
{
get { return (string)GetValue(GameNameProperty); }
set { SetValue(GameNameProperty, value); }
}
public static readonly DependencyProperty GameNameProperty =
DependencyProperty.Register(GameNamePropertyName, typeof(string), typeof(GameIconControl), new UIPropertyMetadata(default(string)));
public BitmapImage Icon
{
get { return (BitmapImage)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register(IconPropertyName, typeof(BitmapImage), typeof(GameIconControl), new PropertyMetadata(default(BitmapImage)));
}
我错过了什么?
答案 0 :(得分:0)
我建议使用Image
来展示Icon
属性,而不是ContentPresenter
。将Icon
属性绑定到Image.Source
,它应该可以正常工作。
答案 1 :(得分:0)
您应该只能使用ImageSource
属性绑定到Image.Source
属性来显示它:
public ImageSource Icon
{
get { return (ImageSource)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register(IconPropertyName, typeof(ImageSource),
typeof(GameIconControl), new PropertyMetadata(null));
...
Icon = new BitmapImage(new Uri("C:\\Image.jpg"));
...
<Image Source="{TemplateBinding Icon}" />
虽然,如果您只是想显示图片,甚至不需要使用ImageSource
数据类型......您只需使用string
路径:
Icon = "C:\\Image.jpg";
or
Icon = "/YourAppName;component/ImageFolderName/ImageName.jpg";
...
<Image Source="{TemplateBinding Icon}" />