WPF数据绑定到对象的properties属性

时间:2020-09-08 14:17:37

标签: c# wpf data-binding

所以我知道有很多数据绑定响应,但是找不到我想要的东西。否则我无法使其正常工作。

在我的情况下,我有一个具有两个属性的类,类型为FootScan,如下所示:

public class ScanResult
{
    public FootScan LeftFoot { get; set; }
    public FootScan RightFoot { get; set; }

    public string Name { get; set; }

    ...
}

public class FootScan
{
    public string ImagePath { get; set; }

    public double FootLength { get; set; }

    ...
}

在我的窗口中,我有这个:

    public ScanResult CurrentScan
    {
        get { return (ScanResult)this.GetValue(CurrentScanProperty); }
        set { this.SetValue(CurrentScanProperty, value); }
    }

    public static readonly DependencyProperty CurrentScanProperty = DependencyProperty.Register(
      "CurrentScan", typeof(ScanResult), typeof(wndScanner), new PropertyMetadata(null));

然后在Window_Loaded上

      CurrentScan = new ScanResult();
      CurrentScan.LeftFoot = new FootScan();
      CurrentScan.LeftFoot.FootLength = 285; //Normally comes from the scan result.

在XAML方面,我想将我的文本块的text属性绑定到CurrentScan.LeftFoot.FootLength:

我尝试了:

1-  <TextBlock x:Name="tbFootLength" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding CurrentScan.LeftFoot.FootLength}" VerticalAlignment="Top" Margin="10,0,0,0" FontFamily="Calibri" FontSize="15"/>
        


2-  <Grid x:Name="grdMeasures" DataContext="{Binding CurrentScan}" Margin="0,35,0,256" Background="#FFE7E7F3">

     <TextBlock x:Name="tbFootLength" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding LeftFoot.FootLength}" VerticalAlignment="Top" Margin="10,0,0,0" FontFamily="Calibri" FontSize="15"/>
   
    </Grid>       


3-   <Grid x:Name="grdMeasures" DataContext="{Binding CurrentScan.LeftFoot}" Margin="0,35,0,256" Background="#FFE7E7F3">

     <TextBlock x:Name="tbFootLength" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding FootLength}" VerticalAlignment="Top" Margin="10,0,0,0" FontFamily="Calibri" FontSize="15"/>
   
    </Grid>   

有想法吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

如果CurrentScan是定义TextBlock的窗口的属性,则此绑定应该起作用:

Text="{Binding CurrentScan.LeftFoot.FootLength, 
    RelativeSource={RelativeSource AncestorType=Window}}"

请不要忘记初始化CurrentScan属性,即进行设置。

相关问题