设置绑定到UserControl的ImageSource依赖项属性时遇到问题

时间:2014-05-09 17:07:03

标签: c# wpf xaml user-controls

我有一个用户WPF UserControl,它只是一个带有Image的网格,我正在将Image投标到名为Source的ImageSource依赖属性。

<UserControl x:Class="ImageOnlyClient.MyImage"
         x:Name="MyImageControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d"             
         d:DesignHeight="300" d:DesignWidth="300">
<Grid Name="MainGrid">
    <Border Name="MyImageBorder" BorderThickness="2" BorderBrush="Orange">
        <Image Name="MyImage" VerticalAlignment="Top" Opacity="1"
               RenderOptions.BitmapScalingMode="NearestNeighbor"
               Source="{Binding Path=Source, Mode=OneWay}" />
    </Border>
</Grid>

在UserControl代码中,我的类定义如下:

public partial class MyImage : UserControl
{
    public ImageSource Source
    {
        get { return (ImageSource)GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }    

    #region Source DependencyProperty
    public static readonly DependencyProperty SourceProperty;

    private static void SourceProperty_PropertyChanged(DependencyObject dobj, DependencyPropertyChangedEventArgs e)
    {
        //To be called whenever the DP is changed.            
        System.Diagnostics.Debug.WriteLine("SourceProperty changed is fired");         
    }

    private static bool SourceProperty_Validate(object Value)
    {
        //Custom validation block which takes in the value of DP
        //Returns true / false based on success / failure of the validation
        //MessageBox.Show(string.Format("DataValidation is Fired : Value {0}", Value));
        return true;
    }

    private static object SourceProperty_CoerceValue(DependencyObject dobj, object Value)
    {
        //called whenever dependency property value is reevaluated. The return value is the
        //latest value set to the dependency property
        //MessageBox.Show(string.Format("CoerceValue is fired : Value {0}", Value));
        return Value;
    }

    #endregion


    static MyImage()
    {
        SourceProperty =  DependencyProperty.Register("Source", typeof(ImageSource), typeof(MyImage),
            new FrameworkPropertyMetadata(null,
                                          FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Journal,
                                          new PropertyChangedCallback(SourceProperty_PropertyChanged),
                                          new CoerceValueCallback(SourceProperty_CoerceValue),
                                          false, UpdateSourceTrigger.PropertyChanged),
                                      new ValidateValueCallback(SourceProperty_Validate));

    }

    public MyImage()
    {
        InitializeComponent();
    }
}

在一个窗口中我尝试使用Image如下并将它的source属性绑定到WritableBitmap(MyClient.ImageMgr.ImageSource),我可以成功绑定到常规的Image控件。

<local:MyImage x:Name="imgPrimaryImage" Height="768" Width="1024" Grid.Column="1" Grid.RowSpan="2"
                 Source="{Binding Path=MyClient.ImageMgr.ImageSource}" />

对于这里发生的事情的任何帮助将不胜感激。我收到以下绑定错误:

  

System.Windows.Data错误:40:BindingExpression路径错误:在'object'''ImageOnly'(Name ='')'上找不到'Source'属性。 BindingExpression:路径=来源; DataItem ='ImageOnly'(Name =''); target元素是'Image'(Name ='MyImage'); target属性是'Source'(类型'ImageSource')

2 个答案:

答案 0 :(得分:2)

您正在尝试将Image的“Source”绑定到父UserControl上的属性,但是如果您没有指定源(我的意思是绑定源......这里的术语令人困惑),那么运行时将在默认数据上下文中查找属性。我会从错误消息中推断出类型为“ImageOnly”的类是用户控件中的继承数据上下文。

您可能只想指定相对来源,如下所示:

<Image ...
       Source="{Binding 
           RelativeSource={RelativeSource AncestorType=UserControl},
           Path=Source, 
           Mode=OneWay}" 
       />

答案 1 :(得分:1)

我终于得到了它的工作@McGarnagle的建议有效,但同时我在UserControl的构造函数中添加了一个DataContext = this,它正在弄乱UserControl的DataContext