找不到 WPF 绑定属性

本文关键字:属性 绑定 WPF 找不到 | 更新日期: 2023-09-27 18:35:25

我在绑定方面有问题。

这一行:Center="{Binding Position, RelativeSource={RelativeSource TemplatedParent}}"导致运行时出现问题。它给了我这个错误:

System.Windows.Data 错误: 40 : 绑定表达式路径错误: 在"对象"上找不到"位置"属性 "内容演示者" (名称=")"。绑定表达式:路径=位置; DataItem='ContentPresenter' (Name='');目标元素为 '椭圆几何' (哈希代码=63639374);目标属性为"中心" (键入"点")

这是我的模型:

public interface IRadarReader
{
    BindingList<RadarEntity> Entities { get; }
    RadarEntity LocalPlayer { get; }
    bool Enabled { get; set; }
}
public class RadarEntity
{
    public Point Position { get; set; }
    public PlayerTeam Team { get; set; }
    public EntityType Type { get; set; }
}

我正在使用System.Windows.Point作为位置。

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:l="clr-namespace:CSGOHack.GUI"
    x:Class="Game.GUI.MainWindow"
    Title="Game Tool" Height="334" Width="415"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
    <l:RadarTeamToColorConverter x:Key="RadarTeamToColorConverter"/>
</Window.Resources>
<Grid>
    <GroupBox Header="Radar">
        <Viewbox>
            <ItemsControl ItemsSource="{Binding GameReader.RadarReader.Entities}" Background="#FFA4D16E">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas Width="100" Height="100"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Path Fill="{Binding Team, Converter={StaticResource RadarTeamToColorConverter}}">
                            <Path.Data>
                                <EllipseGeometry x:Name="PlayerEllipse"
                                    Center="{Binding Position, RelativeSource={RelativeSource TemplatedParent}}"
                                    RadiusX="5"
                                    RadiusY="5"/>
                            </Path.Data>
                        </Path>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </Viewbox>
    </GroupBox>
</Grid>

在 Snoop 2.8.0 中,我可以看到其余内容已正确绑定。值转换器正在工作。只有这个"位置"属性在 Snoop 中突出显示为红色并显示错误。

错误在哪里?

找不到 WPF 绑定属性

{TemplatedParent}不起作用,因为当您从错误中读取时,它会解析为ContentPresenter。如果你对原因感兴趣,你应该真正用Snoop检查可视化树。

但是,我加倍认为@Hamlet答案有效。EllipseGeometry元素不继承DataContextEllipseGeometry元素不在可视化树中。

你可以试试这个:

Center="{Binding DataContext.Position, RelativeSource={RelativeSource TemplatedParent}}"

为什么要绑定诱惑的父母?这应该有效。

<Path.Data>
    <EllipseGeometry x:Name="PlayerEllipse"
                Center="{Binding Position}"
                RadiusX="5"
                RadiusY="5"/>
</Path.Data>