按钮命令绑定

时间:2013-10-02 14:48:29

标签: c# wpf xaml binding

我在列表框中有一个按钮。 我想将命令绑定到主网格的DataContext。 我不知道该怎么做,下面是我的尝试。

我想绑定到我的视图模型上的ViewModel.SelectionEditorSelectionSelectedCommand,主网格绑定到,我不想绑定到实际的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}"
                                    />
    .....

3 个答案:

答案 0 :(得分:2)

使用ElementName绑定到网格应该有效,但是您在绑定语法中发生了一个小错误。 ElementName必须包含名称​​ only ,而不是属性。您只需在DataContext

中添加Path即可
Command="{Binding ElementName=MainGrid,
                  Path=DataContext.SelectionEditorSelectionSelectedCommand}"

答案 1 :(得分:1)

所以基于这一行:

Command="{Binding ElementName=MainGrid.DataContext ... }

我假设你有类似的东西:

<Grid Name="MainGrid">
    <Grid.DataContext>
        <lol:GridViewModel /> <!--Some kind of view model of sorts-->
    </Grid.DataContext>
    ... content
</Grid>

然后你要做的就是在ViewModel类上创建一个返回某种ICommand的公共属性,例如:

class GridViewModel {
    public ICommand SelectionEditorSelectionSelectedCommand { 
        get { return new TestCommand(); } 
    }
}

其中TestCommand是某种实现ICommand的类,如:

class TestCommand : ICommand {
    public event EventHandler CanExecuteChanged { get; set; }

    public bool CanExecute(object parameter)
    {
        return true; // Expresses whether the command is operable or disabled.
    }

    public void Execute(object parameter)
    {
         // The code to execute here when the command fires.
    }
}

基本上,对于ICommand,您只需要定义命令Executes时会发生什么,如何确定它是否CanExecute然后为{{1}提供事件句柄}}。完成此设置后,您只需按下按钮即可:

CanExecuteChanged

就是这样。基本上,绑定会自动检查ViewModel类中是否有一个名为<Button Command="{Binding SelectionEditorSelectionSelectedCommand}" /> 的属性,它实现了SelectionEditorSelectionSelectedCommand。当它读取属性时,它将实例化ICommand的实例,WPF将从那里处理它。单击按钮时,TestCommand将像发条一样被触发。

答案 2 :(得分:0)

你应该像我在类似情况下那样尝试:

<Button Command="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid}}, Path=DataContext.YOURCOMMANDHERE}" />

我在TabItem标题中有一个按钮,它工作正常! 问题是,你的Command是DataContext的一个属性,所以你的路径应该表明它。

祝你好运!

编辑:元素名称也可以。