C# 设置绑定到UserControl的ImageSource依赖项属性时出错

C# 设置绑定到UserControl的ImageSource依赖项属性时出错,c#,wpf,xaml,user-controls,C#,Wpf,Xaml,User Controls,我有一个用户WPF UserControl,它只是一个网格,其中包含一个图像,我将图像绑定到名为Source的ImageSource依赖属性 <UserControl x:Class="ImageOnlyClient.MyImage" x:Name="MyImageControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="htt

我有一个用户WPF UserControl,它只是一个网格,其中包含一个图像,我将图像绑定到名为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>
在一个窗口中,我尝试如下使用图像,并将其源属性绑定到一个可写位图(MyClient.ImageMgr.ImageSource),我可以成功地将该位图绑定到一个常规图像控件

<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路径错误:“在”“对象”“ImageOnly”“(名称=“”)”上找不到“源”属性。BindingExpression:Path=Source;DataItem='ImageOnly'(名称=“”);目标元素是“Image”(Name='MyImage');目标属性为“源”(类型为“ImageSource”)


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

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

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


我终于成功了@McGarnagle的建议奏效了,但与此同时,我在UserControl的构造函数中添加了一个DataContext=this,它弄乱了UserControl的DataContext

ImageOnly是我的测试窗口的类名,该窗口正在使用UserControl。执行此操作后,错误现在是:System.Windows.Data错误:40:BindingExpression路径错误:“SemClient”属性不是在“对象”“MyImage”(Name='imgPrimaryImage')上找到。BindingExpression:Path=MyClient.ImageMgr.ImageSource;DataItem='MyImage'(Name='imgPrimaryImage');目标元素是“MyImage”(Name='imgPrimaryImage');目标属性为“源”(类型为“ImageSource”)
<Image ...
       Source="{Binding 
           RelativeSource={RelativeSource AncestorType=UserControl},
           Path=Source, 
           Mode=OneWay}" 
       />