爱影博客

记录生活 知识分享

解决System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor

在使用VS给控件的某个属性绑定数据的时候出现了这个问题,奇怪的是这个错误是运行时又控制台打印出来的,并不是致命错误。一下是报错的代码:

<Window x:Class="MyGauge.MainWindow"
        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:local="clr-namespace:MyGauge"
        mc:Ignorable="d"
        Title="MainWindow" Height="472" Width="1228.372" Loaded="Window_Loaded">
    <Grid>
        <local:UserControl1 x:Name="mybp" Margin="150,40,758,101"  
        PointerAngle="{Binding PointerAngle, RelativeSource={RelativeSource FindAncestor, 
        AncestorType={x:Type local:UserControl1}}}" PointerValue="2"/>

    </Grid>
</Window>

其中,我要绑定的属性是PointerAngle这个值,正确的方法应该是:

<Window x:Class="MyGauge.MainWindow"
        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:src="clr-namespace:MyGauge"
        xmlns:local="clr-namespace:MyGauge"
        mc:Ignorable="d"
        Title="MainWindow" Height="472" Width="1228.372" Loaded="Window_Loaded">
    <Grid>
        <local:UserControl1 x:Name="mybp" Margin="150,40,758,101" 
        PointerAngle="{Binding PointerAngle, RelativeSource={RelativeSource FindAncestor, 
        AncestorType={x:Type src:MainWindow}}}" PointerValue="2"/>

    </Grid>
</Window>

即加上xmlns:src="clr-namespace:MyGauge"这一句,且把AncestorType={x:Type local:UserControl1}改为AncestorType={x:Type src:MainWindow}即可

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注