[英]Binding a property of an object of a class inside another doesn't work
I have an strange problem with binding in WPF
. 我在WPF
绑定有一个奇怪的问题。 There is a simple sample of what i'm doing: 有一个简单的示例我在做什么:
public class Project
{
private string _title;
public string Title
{
get { return _title; }
set
{
_title= value;
RaisePropertyChanged("Title");
}
}
}
public class People
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name= value
RaisePropertyChanged("Name");
}
}
private Project _project;
public Project Project
{
get { return _project; }
set
{
_project= value;
RaisePropertyChanged("Project");
}
}
}
Now I bound a grid to an instance of People in the view and it can bind controls to Project and Name of People class, but I really can't understand why I can not bind to Project.Title
. 现在,我将网格绑定到视图中的People实例,并且可以将控件绑定到Project和Name of People类,但是我真的不明白为什么不能绑定到Project.Title
。
I write my XAML
code like this: 我这样写我的XAML
代码:
<TextBox Text="{Binding Name}"/>
<Combobox .... SelectedItem="{Binding Project}"/>
<TextBox Text="{Binding Project.Title}"/>
The first two controls above get bounded correctly but the last TextBox
doesn't. 上面的前两个控件正确地有界,但最后一个TextBox
没有。 I have no idea why it can access to Project
but not Project.Title
? 我不知道为什么它可以访问Project
但不能访问Project.Title
? It's an another weird thing I've already seen in WPF! 这是我在WPF中已经看到的另一件事!
Perhaps your combo box selection is not setting the selected value without using Mode=TwoWay
: 也许您的组合框选择没有设置设置值而不使用Mode=TwoWay
:
<Combobox .... SelectedItem="{Binding Project, Mode=TwoWay}"/>
Once the Project
is set, the property is set, the Title
will show. 设置Project
,设置属性,将显示Title
。
Try "Path=Project.Title". 尝试“ Path = Project.Title”。 Worked for me in a same case. 在同一案例中为我工作。
if your DataContext is an instance of your Person object it should work. 如果您的DataContext是Person对象的实例,则它应该可以工作。 you can check your bindings at runtime with Snoop ( http://snoopwpf.codeplex.com/ ) btw. 您可以在运行时使用Snoop( http://snoopwpf.codeplex.com/ )btw检查绑定。 give it a try :) 试试看 :)
you can also do 你也可以
<TextBox DataContext="{Binding Project, Mode=OneWay}" Text="{Binding Title}"/>
谢谢大家,但问题不是我的想法。实际上我使用PropertyChanged.Fody将INotifyPropertyChanged
注入属性,但似乎未达到我的预期。我自己实现了INotifyPropertyChanged
,现在可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.