2010-09-15 36 views
0

我有一個Silverlight用戶控件,其中包含一個Image控件。該圖像需要通過包含上述控件的另一個頁面通過項目的綁定列表的數據項設置。目前,當URL通過用戶控件發送時,圖像不會被設置。實際上,除了SetValue(ImageSourceProperty, value);以外,其他代碼似乎都沒有被擊中。未設置Silverlight 4用戶控件中的圖像

的XAML用戶控件如下所示:

<Grid x:Name="LayoutRoot" Background="Black"> 
    <Image Name="ContentImage"/> 
</Grid> 

在那後面的代碼我有一個DependencyObject的設置爲接收圖像的URL,並設置圖像的數據源:

 public static DependencyProperty ImageSourceProperty = 
    DependencyProperty.Register("ImageSource", typeof(String), typeof(MediaItemControl), null); 

public String ImageSource 
    { 
     get { return (String)GetValue(ImageSourceProperty); } 
     set 
     { 
      SetValue(ImageSourceProperty, value); 
      Dispatcher.BeginInvoke(() => this.ContentImage.Source = new BitmapImage(new Uri(value, UriKind.RelativeOrAbsolute))); 
     } 
    } 

MainPage.Xaml在ItemTemplate中持有對此用戶控件的引用,它在代碼後面的代碼中設置了一個對象列表,其中有一個名爲ImageURL的屬性。該數據源在後面的代碼中正確設置。這是對的MainPage XAML:

<UserControl x:Class="ExampleSilverlightApp.MainPage" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:medc="clr-namespace:ExampleSilverlightApp.Controls" mc:Ignorable="d" 
d:DesignHeight="300" d:DesignWidth="400"> 

<Grid x:Name="LayoutRoot" Background="White"> 
    <StackPanel Name="ItemsControlStackPanel"> 
     <ItemsControl Name="ContentItemControl" Visibility="Visible"> 
      <ItemsControl.ItemsPanel> 
       <ItemsPanelTemplate> 
        <StackPanel Orientation="Horizontal" /> 
       </ItemsPanelTemplate> 
      </ItemsControl.ItemsPanel> 
      <ItemsControl.ItemTemplate> 
       <DataTemplate> 
        <Grid Width="126" HorizontalAlignment="Center"> 
         <medc:MediaItemControl x:Name="CustomMediaItemControl" 
               ImageSource="{Binding ImageURL}" 
               > 
         </medc:MediaItemControl> 
        </Grid> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 
    </StackPanel> 
</Grid> 

我的問題是,圖像源沒有得到用戶控制設置。依賴對象的setter似乎沒有被擊中。如果我在控件上放置了一個按鈕,當按下該按鈕時,設置ImageSource屬性,然後點擊該集合並顯示圖像。有趣的部分是ImageSource值HAS實際上已經正確設置,但圖像的數據源爲空,直到使用按鈕設置。

有沒有人有任何想法,爲什麼發生這種情況?

回答

1

嘗試在依賴屬性的PropertyChangedCallback代表設置ContentImage.Source - 這樣的:

public static DependencyProperty ImageSourceProperty = 
DependencyProperty.Register("ImageSource", typeof(String), typeof(MediaItemControl), 
    new PropertyMetadata(delegate(DependencyObject sender, DependencyPropertyChangedEventArgs args) 
      { 
       (sender as MediaItemControl).ContentImage.Source = new BitmapImage(new Uri((string)args.NewValue, UriKind.RelativeOrAbsolute)); 
      })); 

當數據綁定,在後臺綁定引擎調用DependencyObject.SetValue(ImageSourceProperty,NEWVALUE),並沒有按不是指實際的propery(即 - 它不調用MediaItemControl.ImageSource = newValue) - 因此setter中的邏輯沒有被調用。

HTH!

+0

謝謝 - 作品100% – Madeleine 2010-09-15 12:08:03

相關問題