【问题标题】:Wpf data binding to an object's properties property [duplicate]Wpf数据绑定到对象的properties属性[重复]
【发布时间】:2020-12-26 22:54:39
【问题描述】:

所以我知道有很多数据绑定响应,但我找不到我要找的东西。或者我无法让它正常工作。

在我的例子中,我有一个类,它有两个属性类型 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 方面我想将我的文本块的文本属性绑定到 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>   

有什么想法吗?

谢谢。

【问题讨论】:

  • CurrentScan 是在哪里定义的?在与TextBlock相同的窗口中?
  • Text="{Binding CurrentScan.LeftFoot.FootLength}" 应该可以工作,前提是您已将 Window 的 DataContext 设置为自身,例如DataContext = this; 在其构造函数中。
  • mm8,我编辑了问题,我添加了 CurrentScan 的初始化部分。
  • @CoskunOzogul:然后尝试设置绑定的来源。看我的回答。
  • 我试试这些解决方案

标签: c# wpf data-binding


【解决方案1】:

如果CurrentScan 是定义TextBlock 的窗口的属性,则此绑定应该有效:

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

别忘了初始化CurrentScan属性,即设置它。

【讨论】:

  • 它不起作用 mm8,我想我错过了什么地方。
  • TextBlock 在窗口中吗?请发布您的完整代码。
  • 它是这样工作的:DataContext = this;负载。并且在 xaml Text="{Binding ElementName=mw, Path=CurrentScan.LeftFoot.FootLength}"。感谢您的帮助。
  • 如果绑定到ElementNameRelativeSource,则不需要DataContext = this