按钮命令绑定 [英] Button Command Binding

查看:79
本文介绍了按钮命令绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在列表框中有一个按钮. 我想将命令绑定到主网格的DataContext. 我不确定是谁做的,这是我的尝试.

I have a button inside a listbox. I want to bind the command to the DataContext of the Main Grid. I'm not sure who to do this, below is my attempt.

我想绑定到主网格所绑定到的视图模型上的ViewModel.SelectionEditorSelectionSelectedCommand

I want to bind to ViewModel.SelectionEditorSelectionSelectedCommand on my view model, which the main grid is bound to, I don't want to bind to the actual filteredSelection.SelectionEditorSelectionSelectedCommand

这是我的XAML

<Grid Name="MainGrid">
   .....
    <ListBox x:Name="MarketsListBox"  Height="Auto" MaxHeight="80" ItemsSource="{Binding Path=FilteredMarkets}" Margin="5" Width="Auto" HorizontalAlignment="Stretch"
                 >
          ListBox.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel Orientation="Horizontal">
                            <Button Height="Auto" 
                                    Content="{Binding FinishingPosition,Converter={StaticResource FinishingPositionToShortStringConverter1}}" 
                                    Foreground="{Binding Path=FinishingPosition, Converter={StaticResource FinishingPositionToColourConverter1}}" 
                                    Margin="2" Width="20"
                                    Command="{Binding ElementName=MainGrid.DataContext, Path=SelectionEditorSelectionSelectedCommand}" 
                                    CommandParameter="{Binding}"
                                    />
    .....

推荐答案

使用ElementName绑定到网格应该可以,但是您在绑定语法上犯了一个小错误. ElementName必须仅包含名称​​ ,而不是属性.您只需要在Path中添加DataContext:

Binding to the grid using ElementName should work, but you have made a small error in the binding syntax. ElementName must include the name only, not a property. You simply need to include DataContext in the Path:

Command="{Binding ElementName=MainGrid,
                  Path=DataContext.SelectionEditorSelectionSelectedCommand}"

这篇关于按钮命令绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆