我第一次尝试 WPF,我正在努力解决如何将控件绑定到使用其他对象的组合构建的类。例如,如果我有由两个单独的类组成的 Comp 类(为清楚起见,请注意省略了各种元素):
class One {
int _first;
int _second;
}
class Two {
string _third;
string _fourth;
}
class Comp {
int _int1;
One _part1;
Two _part2;
}
现在我知道我可以使用 Comp 中定义的“get”轻松绑定 _int1。但是我如何绑定到元素_part1._first、_part1._second。我是否在类 Comp 级别为他们公开了“吸气剂”?或者我可以在复合类中公开它们并使用指向它们的绑定路径?以及如何设置属性?
这就是模式吗?
....
<TextBlock Name="txtBlock" Text="{Binding Path=Third}" />
....
class One {
int _first;
int _second;
}
class Two {
string _third;
string _fourth;
}
class Comp {
int _int1;
One _part1;
Two _part2;
int Int1 { get { return _int1; } set { _int1 = value; } }
int First { get { return _part1._first; } set { _part1._first = value; } }
int Second { get { return _part1._second; } set { _part1._second = value; } }
string Third { get { return _part2._third; } set { _part2._third = value; } }
string Fourth { get { return _part2.fourth; } set { _part2._fourth = value; } }
}
...
Comp oComp = new Comp();
txtBlock.DataContext = oComp;
...
或者这就是模式?(我不知道该放什么路径)
....
<TextBlock Name="txtBlock" Text="{Binding Path=_part2.Third}" />
....
class One {
int _first;
int _second;
int First { get { return _first; } set { _first = value; } }
int Second { get { return _second; } set { _second = value; } }
}
class Two {
string _third;
string _fourth;
string Third { get { return _third; } set { _third = value; } }
string Fourth { get { return _fourth; } set { _fourth = value; } }
}
class Comp {
int _int1;
One _part1;
Two _part2;
int Int1 { get { return _int1; } }
}
...
Comp oComp = new Comp();
txtBlock.DataContext = oComp;
...
还是我正在重新发明 MV-VM(我正在慢慢开始理解)?
....
<TextBlock Name="txtBlock" Text="{Binding Path=Third}" />
....
class One {
int _first;
int _second;
}
class Two {
string _third;
string _fourth;
}
class Comp {
int _int1;
One _part1;
Two _part2;
}
class CompView {
Comp _comp;
CompView( Comp comp ) {
_comp = comp;
}
int Int1 { get { return _comp._int1; } set { _comp._int1 = value; } }
int First { get { return _comp._part1._first; } set { _comp._part1._first = value; } }
int Second { get { return _comp._part1._second; } set { _comp._part1._second = value; } }
string Third { get { return _comp._part2._third; } set { _comp._part2._third = value; } }
string Fourth { get { return _comp._part2.fourth; } set { _comp._part2._fourth = value; } }
}
...
Comp oComp = new Comp();
CompView oCompView = new CompView( oComp );
txtBlock.DataContext = oCompView;
...
那么我该怎么做呢?如果它是第一个或第三个模式,那么我似乎已经获取了我所有可爱的(不同的)层次结构数据并将其分解为一个平面配置,以便我可以将它绑定到 UI 元素。这是它必须发生的方式,还是有更好的方法(第二种模式??)
编辑
我忽略了我真的想要两种方式绑定的问题。所以属性访问器真的应该有get和set。
编辑
更新了我的伪代码以显示 setter 和 getter
编辑
我遵循 Mark 和 Julien 提供的模式并实现了 setter,并对结果感到满意。出于某种原因,我说服自己,属性的设置不会一直跟随到最终实体。