我目前編寫的圖像查看器控件封裝了一個WPF圖像控件和更多的東西(用於應用過濾器和改變視圖的控件)。下面是控件的源代碼中的相關部分:用戶控件的用戶控件與自定義類型依賴屬性(Bound)
public partial class ImageViewPort : UserControl, INotifyPropertyChanged
{
private BitmapSource _source;
public static readonly DependencyProperty ImageDescriptorSourceProperty =
DependencyProperty.Register("ImageDescriptorSource",
typeof(ImageDescriptor),
typeof(ImageViewPort),
new UIPropertyMetadata(ImageDescriptorSourceChanged));
public ImageDescriptor ImageDescriptorSource
{
get { return (ImageDescriptor)GetValue(ImageDescriptorSourceProperty); }
set { SetValue(ImageDescriptorSourceProperty, value); }
}
public BitmapSource Source //the image control binds to this beauty!
{
get { return _source; }
set { _source = value; OnPropertyChanged("Source"); }
}
public ImageViewPort() { InitializeComponent(); }
private static void ImageDescriptorSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ImageViewPort viewPort = (ImageViewPort)d;
if (viewPort != null)
{
viewPort.TransformImage();
}
}
private BitmapSource TransformImage()
{
//do something that sets the "Source" property to a BitmapSource
}
}
的XAML代碼(僅相關部分):
<UserControl x:Name="viewPort">
<Image Source="{Binding ElementName=viewPort,Path=Source}"/>
</UserControl>
最後用法:
<WPF:ImageViewPort ImageDescriptorSource="{Binding Path=CurrentImage}"/>
在我窗口,我基本上迭代一個集合,併爲我這樣做,爲CurrentImage屬性拋出PropertyChanged通知。這是有效的,每次都會調用getter,所以綁定似乎工作。
現在我想要發生的是我的UserControl的PropertyChanged回調被觸發,但沒有發生這種事情(它從來沒有在那裏的步驟,我試過使用斷點)。我試過綁定一個基本類型(int)的相同的東西,並且工作。
您是否看到我的實施中存在缺陷?爲什麼不更新用戶控件? 非常感謝您的幫助!
乾杯
塞比
檢查輸出...你有任何綁定警告?你還設置了一個新的價值? WPF知道你什麼時候嘗試設置一個已經設置的值並忽略它。我建議將元數據類型轉換爲FrameworkPropertyMetadata並提供適當的默認值。 – dowhilefor 2012-01-17 12:33:48
這個'{Binding ElementName = viewPort,Path = Source}' 意味着你的'viewPort'元素有'Source' DP,這看起來並不是這樣,是你實際使用的XAMl? – 2012-01-17 12:39:18
@dowhilefor:在我的控制檯窗口中,多麼愚蠢地忘記數據綁定異常:)謝謝! – 2012-01-17 12:41:18