SilverLight - MVVM binding viewmodel property to datagrid column

廉价感情. 提交于 2019-12-12 20:29:22

问题


In my SilverLight application, I have a property in my ViewModel called 'vmProperty' and a list called 'dgSource'.

I bind my dgSource to the datagrid as ItemsSource at which point each datagrid row's datacontext changes to each item in dgSource. One of the columns, say a checkbox column, needs to bind to vmProperty. But since the ViewModel is no longer the row's datacontext, I cannot get access to this property.

How do I get around this problem? If the question is not clear, please let me know and I will post a sample. Thanks in advance.


回答1:


Assuming your ViewModel is assigned as the LayoutRoot's DataContext this should work:-

IsChecked="{Binding DataContext.vmProperty, ElementName=LayoutRoot}"

Of course this doesn't work, ultimately a template is replicated and therefore "LayoutRoot" does not exist in the namescope where the binding is actually used.

The simplest solution since this is a ViewModel is to change the model. Expose the required value on the objects available in the dgSource or expose a Parent property that navigates back to the ViewModel.




回答2:


Try to set checked property of your chechbox column to that:

{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourViewClassName}}, Path=DataContext.vmProperty}

That's mean that parent element which type is your view type will be found and than vmProperty of it's DataContext will be retrieved as value.

UPDATE:

It was solution for WPF.

For silverlight I think you can try to use construction like this:

{Binding Path=DataContext.vmProperty, ElementName=YourElement}

Where DataContext of YourElement is instance of your view model. I think it can be a grid for example.

<Grid x:Name="YourElement" DataContext={Binding}>
<!-- DataGrid here -->
</Grid>


来源:https://stackoverflow.com/questions/1825454/silverlight-mvvm-binding-viewmodel-property-to-datagrid-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!