开发者

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?


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}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜