Travis Boatman
Travis Boatman

Reputation: 2282

Chaning the ItemsSource DataContext

I'm having a problem binding to my command in my ListBox ItemTemplate. My command is defined in my ViewModel, but because I'm using ItemsSource for my listbox, that's set as the DataContext.

                 <ListBox ItemsSource="{Binding CreatureModel.TypeFlagsValues}">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <CheckBox Content="{Binding}" Command="{Binding SetCommand">
                                </CheckBox>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>

I've tried using RelativeSource

Command="{Binding SetCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vm:CreatureEditorViewModel}}}"

And

    <DataTemplate DataType="vm:CreatureEditorViewModel">
         <CheckBox Content="{Binding}" Command="{Binding SetCommand}" CommandParameter="test">
         </CheckBox>
    </DataTemplate>

I feel like I'm missing something simple here.

Upvotes: 0

Views: 41

Answers (2)

Volodymyr Dombrovskyi
Volodymyr Dombrovskyi

Reputation: 269

You almost did it right with RelativeSource.

Try this:

Command="{Binding Path=DataContext.SetCommand, 
                    RelativeSource={RelativeSource Mode=FindAncestor,      
                    AncestorType={x:Type ItemsControl}} }"

Alternatively you may give a name to your listbox (e.g. "_listBox" and use the following binding:

Command="{Binding DataContext.SetCommand, ElementName=_listBox}

Upvotes: 1

Stefano Castriotta
Stefano Castriotta

Reputation: 2913

Try setting the ElementName and Path on the Command; you have to set the x:Name on the ListBox, then you can reference the parent DataContext.

<ListBox x:Name="list" ItemsSource="{Binding CreatureModel.TypeFlagsValues}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding}" Command="{Binding ElementName=list,
               Path=DataContext.SetCommand}">                    
            </CheckBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 0

Related Questions