【问题标题】:WPF - How to bind to a Dependency Property of custom classWPF - 如何绑定到自定义类的依赖属性
【发布时间】:2010-08-04 05:22:42
【问题描述】:

我再次陷入 WPF 绑定地狱 :) 我有一个公共课程 (Treatment),如下所示:

public class Treatment()  
{  
...    
    public Ticker SoakTimeActual;   
...  
}

Ticker 内是一个依赖属性:

public class Ticker : FrameworkElement
{     
    // Value as string
    public static readonly DependencyProperty DisplayIntervalProperty = DependencyProperty.Register("DisplayInterval", typeof(string), typeof(Ticker), null);
    public string DisplayInterval
    {
        get { return (string)GetValue(DisplayIntervalProperty); }
        set { SetValue(DisplayIntervalProperty, value); }
    }
    ...
}

在我的应用程序中,创建了一个 Treatment 对象,并且可以在 XAML 中轻松访问(在 app.xaml 中):

<Application.Resources>
   <ResourceDictionary>
      <u:Treatment
         x:Key="currentTreatment" />
   </ResourceDictionary>
</Application.Resources>

现在,我需要绑定到 SoakTimeActualDisplayInterval 依赖属性,以在当前状态下显示此文本。这是我的尝试,但不起作用:

<TextBlock              
   Text="{Binding Source={StaticResource currentTreatment}, Path=SoakTimeActual.DisplayInterval}"/>

这当然可以编译,但不会显示任何内容。我假设我在更改通知或DataContext 或两者方面都犯了错误。

感谢任何见解!

【问题讨论】:

    标签: data-binding dependency-properties


    【解决方案1】:

    WPF 绑定仅作用于属性,而不作用于字段。

    因此,您需要将 SoakTimeActual 字段更改为属性,如下所示:

    public class Treatment
    {  
    ...    
        public Ticker SoakTimeActual { get; set; }
    ...  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2013-10-16
      • 2010-11-25
      相关资源
      最近更新 更多