2011-12-21 150 views
0

我正在创建一个使用其内部图像的自定义WPF控件。这个自定义控件将像其他任何控件一样,将在xaml中声明。我想有此控件的公共属性来指定内部图像的来源,多你使用Image控件时,做到这一点是相同的:在xaml中设置控件属性

<Image Source="http://foo.com/bar.jpg"></Image> 

我想要做的是有以下用法我的控制:

<MyCustomControl ImageSource="http://foo.com/bar.jpg"></MyCustomControl> 

,然后在内部,像:

<UserControl class="MyCustomControl" ...> 
    <Image Source="{Binding Imagesource}"></Image> 
</UserControl> 

我需要在我隐藏什么样的设置来得到这个工作?我已经尝试了一些东西,但没有任何工作。

+0

你问的是如何创建'ImageSource'?如果是这样,你正在寻找一个DependencyProperty。或者你问如何将DependencyProperty链接到封装控件? – MBirchmeier 2011-12-21 21:09:27

回答

2

你需要的是ImageSource类型和适当结合的dependency property,要么使用ElementNameRelativeSource,不要UserControls使用DataContext

<UserControl Name="control" x:Class="MyCustomControl" ...> 
    <Image Source="{Binding ImageSource, ElementName=control}"/> 
</UserControl> 

<UserControl x:Class="MyCustomControl" ...> 
    <Image Source="{Binding ImageSource, 
          RelativeSource={RelativeSource AncestorType=UserControl}}"/> 
</UserControl> 
+0

只是出于好奇 - 与用户控件使用DataContext拧什么? – 2011-12-21 23:21:41

+1

@Dmitry:通常期望DataContext被继承,除非明确设置,问题是当DataContext在UserControl中设置时,它在实例中*甚至不可见*,并且由于预期不同的DataContext,绑定将意外失败。 – 2011-12-21 23:52:19

+0

奇怪的是,这工作在我的silverlight应用程序,但不是我的WPF应用程序。任何想法为什么? – PhilBrown 2011-12-22 14:26:55