绑定到Usercontrol Datacontext而不是SelectedItems datacontext

时间:2014-08-19 19:02:00

标签: c# wpf datacontext

我有一个列表框,其中带有文本框的网格显示列表框当前选择的项目数据。 (以下代码)

问题是我想在这个网格中有一个删除按钮,但是它使用的命令位于Usercontrols DataContext中。如何使按钮接收UserControls Datacontext中的命令绑定?

以下代码位于网格内,其中可视树根是UserControl。

        <ListBox Name="list" ItemTemplate="{StaticResource listTemplate}" ItemsSource="{Binding listCollection, UpdateSourceTrigger=PropertyChanged}">
        </ListBox>

        <Grid DataContext="{Binding ElementName=list, Path=SelectedItem}" Grid.Row="1">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Margin="7">Name:</TextBlock>
        <TextBox Margin="5" Grid.Column="1" Text="{Binding Path=Name}"></TextBox>
        <Button Grid.Row="1" Command="{Binding DeleteSelectedItemCommand}">Delete Selected Item</Button>
        </Grid>

3 个答案:

答案 0 :(得分:1)

你的意思是你想在你的用户控件DataContext IE上发出按钮的命令吗? 然后你需要这个绑定;

<Button Grid.Row="1" Command="{Binding Path=DeleteSelectedItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourControl}}}">Delete Selected Item</Button>

基本上这只是遍历你的xaml树并从名为YourControl的控件中获取datacontext。你可以在这里设置UserControl。关于这种绑定的一个很酷的事情是你可以跟踪链中任何项目的datacontext:)

This document is still very handy for bindings that are a bit tricky :)

干杯,

了Stian

答案 1 :(得分:1)

您需要更改DataContext,为UserControl提供相同的名称,然后

Command="{Binding ElementName=Name, Path=DeleteSelectedItemCommand}"

答案 2 :(得分:0)

诀窍是使用Stians引用连接DataContext。

<Button 
DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType {x:Type UserControl}}, Path=DataContext}" 
Command="{Binding Path=DeleteSelectedItemCommand}">
</Button>
相关问题