2012-01-17 75 views
0

我目前编写的图像查看器控件封装了一个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)的相同的东西,并且工作。

您是否看到我的实施中存在缺陷?为什么不更新用户控件? 非常感谢您的帮助!

干杯

塞比

+0

检查输出...你有任何绑定警告?你还设置了一个新的价值? WPF知道你什么时候尝试设置一个已经设置的值并忽略它。我建议将元数据类型转换为FrameworkPropertyMetadata并提供适当的默认值。 – dowhilefor 2012-01-17 12:33:48

+0

这个'{Binding ElementName = viewPort,Path = Source}' 意味着你的'viewPort'元素有'Source' DP,这看起来并不是这样,是你实际使用的XAMl? – 2012-01-17 12:39:18

+0

@dowhilefor:在我的控制台窗口中,多么愚蠢地忘记数据绑定异常:)谢谢! – 2012-01-17 12:41:18

回答

1

检查输出...你得到任何有约束力的警告?你还设置了一个新的价值? WPF知道你什么时候尝试设置一个已经设置的值并忽略它。我建议将元数据类型转换为FrameworkPropertyMetadata并提供适当的默认值。

给这个“评论”更多的价值:在绑定上添加“PresentationTraceSources.TraceLevel = High”会提供更多关于绑定如何获取其值的信息,这也有助于找到非错误的问题WPF。

<TextBox Text="{Binding MyText, PresentationTraceSources.TraceLevel=High}"/> 
+0

谢谢,甚至更多关于TraceLevel的信息 - 这就是我一直在寻找的一段时间! – 2012-01-17 13:44:52