【问题标题】:How do I bind a close button in a TabControl header to a command in the window's ViewModel?如何将 TabControl 标头中的关闭按钮绑定到窗口 ViewModel 中的命令?
【发布时间】:2013-03-13 05:31:54
【问题描述】:

我正在开发一个工具,并希望在 TabControl 中的选项卡上添加一个关闭按钮。我不知道如何将按钮的 Command 属性绑定到我的窗口 ViewModel 上的相应属性。

虚拟机很简单。只是 INPC 实现和一个名为 CloseSelectedFileCommand 的 ICommand 属性。

省略了其他部分的 TabControl 的 XAML,没有什么漂亮的,因为漂亮是在“它可以工作”之后:

<TabControl ItemsSource="{Binding Results}" 
            SelectedItem="{Binding SelectedFile}">
    <TabControl.ItemTemplate>
        <!-- Type is ResultInfo -->
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding FileName}" />
                <Button Grid.Column="1" Command="{Binding Path=CloseSelectedFileCommand}">X</Button>
            </Grid>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
          ...
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

我明白发生了什么。从按钮的角度来看,当前项目是我收藏的项目之一。他们没有 DataContext,如果他们这样做了,肯定不会是我的 Window 的 ViewModel。我不知道如何使这项工作。我认为寻找 Window 祖先的 RelativeSource 可能会有所帮助,但它没有。

我查看了一些 Google 搜索。他们似乎建议我的数据项本身应该是一个 ViewModel 并且上面有这个命令。这......有点奇怪,因为项目集合属于窗口。类似的 StackOverflow 帖子似乎建议自己制作绑定项目 ViewModel,并为它们提供一个引发由窗口处理的事件的命令。我不明白“按钮在单击时引发事件”之上的额外间接层对我有什么作用。我想这是唯一的方法?我想不出办法将 Window 的 DataContext 传送到这个 XAML。

【问题讨论】:

  • 你的 windows DataContext 是你的 ViewModel 吗?或者什么元素有你的 ViewModel,因为你可以使用 ElementName 绑定,例如Command="{Binding Path=CloseSelectedFileCommand, ElementName=myWindowOrControlName}"
  • 是的,Window的DataContext就是ViewModel。到目前为止,看起来 NSGaga 给出的答案是可行的,我正在使用它。

标签: wpf


【解决方案1】:

也许这对你有用,在这些方面......
绑定 Button 的数据上下文(或您可能需要的任何其他地方)...

DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext}"  

这为您提供“上方”某处的窗口。

或者,如果您有特定的Name,您可以使用ElementName,类似于RelativeSource

希望对你有帮助

【讨论】:

  • 我发誓我尝试过类似的方法,但我想我错了。您的回答让我尝试:Command="{Binding Path=DataContext.CloseSelectedFileCommand,RelativeSource={RelativeSource AncestorType=Window}}"
  • 是的,尝试一些事情直到满足您的要求,很高兴它有所帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-17
  • 2020-05-28
  • 2012-09-03
相关资源
最近更新 更多