Fel*_*x C 12 c# wpf binding mvvm
我有一个具有复杂属性类型的ViewModel,并希望将我的视图绑定到此对象的嵌套属性.
我的ViewModel正在实现INotifyPropertyChanged
(或者确实是extact BaseViewModel
正在实现它).父属性的类未实现INotifyPropertyChanged
.
当我更新父属性的值时,嵌套属性不会更新.你能告诉我如何实现这个功能吗?
视图模型
public class ViewModel : BaseViewModel
{
private Car _myCarProperty;
public Car MyCarProperty
{
get { return _myCarProperty; }
set
{
if (value == _myCarProperty) return;
_myCarProperty = value;
OnPropertyChanged();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在视图中绑定
<TextBlock Text="{Binding Path=MyCarProperty.Manufacturer}" />
Run Code Online (Sandbox Code Playgroud)
当我更改MyCarProperty
View 的值时不更新.
谢谢你的帮助!
编辑:OnPropertyChanged()实现
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion INotifyPropertyChanged
Run Code Online (Sandbox Code Playgroud)
Gre*_*g D 17
"Car类没有实现INotifyPropertyChanged.但是我没有更改属性Manufacturer,我更改了MyCarProperty属性,所以我希望OnNotifyPropertyChanged事件会触发值更新?"
不,它不会触发值更新级别.绑定不会监听整个路径的属性更改,它们只监听它们绑定的对象.
我在头顶看到了几个选项(当我遇到这个时,按照我的偏好顺序):
BindingExpression
在需要时通过调用UpdateTarget来手动踢绑定.我知道它看起来像有很多东西要学数据模板路线上,但我向你保证,数据模板将证明大大正如你在WPF工作超过手动踢绑定功能更强大,可扩展性,可维护性和有用的.(另外,一旦你了解它们,我认为它们实际上比手动踢绑定更少).
祝好运!
接受的答案说明了如何处理以下情况:绑定源的子属性已更改,而您希望更新视图-这不是问题要问的内容。实际上,只要您为指定路径内正在更改的任何属性通知更改,WPF就会从许多级别向下响应更改。
至于:
“汽车类未实现INotifyPropertyChanged。但是我没有更改制造商属性,而是更改了MyCarProperty属性,因此我希望OnNotifyPropertyChanged事件将触发值更新吗?”
WPF已经对此进行了处理。
在您的示例中,ViewModel
是绑定源。设置MyCarProperty
(触发NotifyPropertyChanged
事件)时,WPF将使用新的 Binding Source对象的Binding Path重新评估Binding Target值-使用new来更新视图Manufacturer
。
我已经使用简单的WPF应用程序进行了测试-对于深度嵌套的路径也是如此:
<!-- When MyViewModel notifies that "MyCarProperty" has changed, -->
<!-- this binding updates the view by traversing the given Path -->
<TextBlock Text="{Binding Path=MyCarProperty.Model.SuperNested[any][thing][you][want][to][try][and][access].Name}" />
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22134 次 |
最近记录: |