【问题标题】:Binding to Usercontrol Datacontext instead of SelectedItems datacontext绑定到 Usercontrol Datacontext 而不是 SelectedItems datacontext
【发布时间】:2014-08-19 19:01:59
【问题描述】:

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

问题是我想要这个网格内的删除按钮,但是它使用的命令位于 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>

【问题讨论】:

    标签: c# wpf datacontext


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答!我无法让它工作,我测试了我的模型是否有效。而且,一旦我删除了整个网格数据上下文,并通过 Command="{Binding Path=DeleteSelectedItemCommand}" 定期将其连接起来,它就可以工作了。介意举个例子吗?
    • 检查你的 UserControl DataContext 是什么。
    【解决方案2】:

    你的意思是你想在你的 UserControls DataContext IE 你的虚拟机上触发按钮的命令? 那么你需要这个绑定;

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

    基本上,这只是遍历您的 xaml 树并从名为 YourControl 的控件中获取数据上下文。您可以在此处设置 UserControl。这种绑定最酷的地方在于,您可以追溯链上任何项目的数据上下文:)

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

    干杯,

    斯蒂安

    【讨论】:

    • 感谢您的回复和方便的链接!一定会喜欢它,但是,我无法让它工作,我测试了我的模型是否有效。而且,一旦我删除了整个网格数据上下文,并通过 Command="{Binding Path=DeleteSelectedItemCommand}" 定期将其连接起来,它就可以工作,对我来说这似乎是一个难题。 (为什么我可以通过 RelativeSource 获得 DC)有什么想法吗?
    • 您将 AncestorType={x:Type YourControl} 中的 YourControl 替换为您的实际根元素,例如 Windows/UserControl,不是吗?
    • RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},我使用的是 UserControl,所以我相信是这样吗?
    • @ETG87 只要您不遇到其他用户控件就可以了,所以在这种情况下应该没问题。如果还有更多,您将不得不在绑定中使用 AncestorLevel。它是定位您想要的用户控件的替代方法。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-07-19
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 2011-07-01
      • 1970-01-01
      • 2016-08-15
      相关资源
      最近更新 更多