Marc
Marc

Reputation: 3

MVVM Nested databinding

I'm having some trouble with databinding inside a UserControl when using an ItemsControl which has an ItemsSource. My Eventtrigger is never called.

I Think the problem is that when I call my eventtrigger in the line:

<cmd:EventToCommand Command="{Binding ElementName=layoutroot, Path=DataContext.Checked}" />

it tries to find the checked event in CheckBoxes collection because i have set my ItemsSource, while it should be looking in its parent . I've been searching for a solution for days, but none of them seem to work.

My code looks like this:

<Grid x:Name="layoutroot">
            <ItemsControl x:Name="itemcontrol" ItemsSource="{Binding CheckBoxes}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Vertical"></StackPanel>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <s:SurfaceCheckBox Background="White" Foreground="White">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="Checked">
                                    <cmd:EventToCommand Command="{Binding ElementName=layoutroot, Path=DataContext.Checked}" />
                                </i:EventTrigger>
                            </i:Interaction.Triggers>
                        </s:SurfaceCheckBox>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </Grid>

When I try the following code it works exactly as expected:

<Grid x:Name="layoutroot">
    <s:SurfaceCheckBox Background="White" Foreground="White" Content="{Binding Content}" >
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Checked">
                <cmd:EventToCommand Command="{Binding ElementName=layoutroot, Path=DataContext.Checked}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </s:SurfaceCheckBox>
</Grid>

But I really need this behaviour inside an itemsControl with a set ItemsSource.

Any ideas?

Upvotes: 0

Views: 626

Answers (1)

bufferz
bufferz

Reputation: 3476

Binding inside of an ItemsControl is placed upon the current Item in the collection. What you need to do is seek out the parent, and Bind from there.

Give this a try from inside your ItemsControl, replacing MyUserControlName:

<cmd:EventToCommand Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyUserControlName} }, Path=DataContext.Checked}" />

Upvotes: 1

Related Questions