2011-12-21 89 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