简体   繁体   中英

Bind ComboBox in DataGrid to collection in view

I have a view that is bound to my usercontrol. On my usercontrol I have a datagrid which is bound to a collection from my view. One column in that datagrid is a DataGridComboBoxColumn and I need to bind it to a different collection in my view. The binding of the datagrid looks like this:

DataContext="{Binding .}" ItemsSource="{Binding VictimVillages}"

The datacontext is the view and VictimVillages is the collection I want to display in the datagrid.

I have tried to access the collection I want to display in the combobox with

ItemsSource="{Binding Path=Patterns,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Views:ViewPlanner}}}"

The name of the collection is Patterns, the type of the view is "ViewPlanner", which is in the Views namespace.

I have create a diagram of the dependencies. I need help to figure out the yellow part. 在此处输入图片说明

when using RelativeSource Binding you(mostly) have to use DataContext.YourProperty in your Binding Path.

if your datacontext from the DataGrid also have the Patterns Collection you can do this

ItemsSource="{Binding Path=DataContext.Patterns,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}"

i often use "MarkerInterface" for Relative bindings. that mean empty interfaces that i can add to my views.

public interface IDataContextMarker4PatternCollection {}

now add this interface to your view/usercontrol where the Pattern Collection Property is in the Datacontext.

and now you can simply use RelativeSourceBinding

 ItemsSource="{Binding Path=DataContext.Patterns,RelativeSource={RelativeSource AncestorType={x:Type local:IDataContextMarker4PatternCollection }}}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM