我无法获取数据绑定到UI。
问题
我是否必须实现DependencyProperty或INotifyPropertyChanged?它简单的数据绑定
我想我不必使用上面的属性。
XMAL CODE
<Window x:Class="Pr.child"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:Pr"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Title="" Height="327" Width="683" WindowStartupLocation="CenterOwner">
<Window.Resources>
<ObjectDataProvider x:Key="Obj" ObjectType="{x:Type src:test}" MethodName="getinfo" />
</Window.Resources>
<Label x:Name="lblTest" Content="{Binding Source={StaticResource Obj},diag:PresentationTraceSources.TraceLevel=High}"</Label>
<Button Name="btnOK" Click="btnOK_Click">OK</Button>
代码背后
主Windows类
public partial class Window1 : Window
{
child w = new child();
}
子窗口类
public partial class child : Window
{
public child ()
{
InitializeComponent();
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
RunTest runTest = new RunTest();
}
}
RunTest runTest
class RunTest
{
public RunTest()
{
test t = new test();
t.info = "test info";
t.getinfo();
}
}
测试类
class test
{
public string info { get; set; }
public string getinfo()
{
return info;
}
}
调试信息
System.Windows.Data Warning: 52 : Created BindingExpression (hash=44780731) for Binding (hash=63630067)
System.Windows.Data Warning: 54 : Path: ''
System.Windows.Data Warning: 56 : BindingExpression (hash=44780731): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=44780731): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=44780731): Attach to System.Windows.Controls.Label.Content (hash=1867017)
System.Windows.Data Warning: 63 : BindingExpression (hash=44780731): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=44780731): Found data context element: <null> (OK)
System.Windows.Data Warning: 73 : BindingExpression (hash=44780731): Use Data from ObjectDataProvider (hash=16906910)
System.Windows.Data Warning: 74 : BindingExpression (hash=44780731): Activate with root item <null>
System.Windows.Data Warning: 100 : BindingExpression (hash=44780731): Replace item at level 0 with <null>, using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=44780731): GetValue at level 0 from <null> using <null>: <null>
System.Windows.Data Warning: 76 : BindingExpression (hash=44780731): TransferValue - got raw value <null>
System.Windows.Data Warning: 85 : BindingExpression (hash=44780731): TransferValue - using final value <null>
答案 0 :(得分:1)
这似乎有道理。您的ObjectDataProvider正在创建 new test
,并在其上调用getinfo
方法。这是null,因为没有任何机会在该新实例上设置信息,实际上您的代码甚至没有对它的引用。
因此标签正确显示了您的跟踪所同意的null值。
如果希望UI对其他对绑定对象所做的更改做出反应,则只需要实现INPC或使用DependencyObjects。但是将某些属性绑定到!
会有所帮助答案 1 :(得分:-2)
我在15分钟前遇到了这种情况。您需要实现DependencyProperty