根据您的回答,我按照以下描述解决了问题。我发布它,因为我认为其他WPF初学者可能会发现它有用。
我有一个单例类(InfoPool.cs),它实现了INotifyChangedProperty。它用于提供应用程序范围内可绑定属性。这个类被App.xaml中的ObjectDataProvider使用。所以很容易绑定到属性。
InfoPool.cs(Singleton代码来自
http://csharpindepth.com/Articles/General/Singleton.aspx第5版。我将Instance属性更改为GetInstance()方法,因为OPD需要一个方法)。
public sealed class InfoPool : INotifyPropertyChanged
{
InfoPool()
{
}
public static InfoPool GetInstance()
{
return Nested.instance;
}
class Nested
{
static Nested()
{
}
internal static readonly InfoPool instance = new InfoPool();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
private String strProp = "default String";
private Double dblProp = 1.23456;
public String StrProp
{
get { return strProp; }
set
{
strProp = value;
OnPropertyChanged(new PropertyChangedEventArgs("StrProp"));
}
}
public Double DblProp
{
get { return dblProp; }
set
{
dblProp = value;
OnPropertyChanged(new PropertyChangedEventArgs("DblProp"));
}
}
App.xaml 中的 ObjectDataProvider
<Application.Resources>
<ResourceDictionary>
<ObjectDataProvider x:Key="OPDInfo" ObjectType="{x:Type local:InfoPool}" MethodName="GetInstance" d:IsDataSource="True"/>
</ResourceDictionary>
</Application.Resources>
这里有两种绑定到OPD的方式
<StackPanel>
<TextBlock x:Name="tbprop1" Text="{Binding Path=StrProp, Source={StaticResource OPDInfo}}" />
<TextBlock x:Name="tbprop2" Text="{Binding DblProp}" ToolTip="{Binding StrProp}" DataContext="{StaticResource OPDInfo}" />
</StackPanel>
就是这样。请评论,因为我对此很新奇;-)