2

我正在使用列表框,它包含按钮,我想使用命令处理按钮单击事件。但我的命令从不调用。

这是正确的方法吗?

  <pmControls:pmListBox Grid.Row="1" Margin="3" ItemsSource="{Binding Countries}" SelectedItem="{Binding SelectedCountry}" >
                <pmControls:pmListBox.ItemTemplate >
                    <DataTemplate >
                        <Button Command="{Binding GetAllStatesCommand}"   CommandParameter="{Binding}" Margin="3" Width="100" Height="50" Content="{Binding Title}">                                                                                                                                
                        </Button>

                    </DataTemplate>
                </pmControls:pmListBox.ItemTemplate>
  </pmControls:pmListBox>
4

1 回答 1

0

DataContext一个列表项的DataContext与周围控件的不同。要将该命令绑定到DataContext该控件的,您有两个选项:

您可以为控件提供名称和对其的引用:

<pmControls:pmListBox x:Name="myCoolListBox" [...]>
    <pmControls:pmListBox.ItemTemplate>
        <DataTemplate>
            <Button Command="{Binding DataContext.GetAllStatesCommand, ElementName=myCoolListBox}" CommandParameter="{Binding}" [...] />                                           
        </DataTemplate>
    </pmControls:pmListBox.ItemTemplate>
</pmControls:pmListBox>

或者你创建类持有你的DataContext......

public class DataContextBinder : DependencyObject
{
    public static readonly DependencyProperty ContextProperty = DependencyProperty.Register("Context", typeof(object), typeof(DataContextBinder), new PropertyMetadata(null));
    public object Context
    {
        get { return GetValue(ContextProperty); }
        set { SetValue(ContextProperty, value); }
    }
}

...并在您的资源部分创建一个实例ListBox

<pmControls:pmListBox x:Name="myCoolListBox" [...]>
    <pmControls:pmListBox.Resources>
        <local:DataContextBinder x:Key="dataContextBinder" Context="{Binding}" />
    </pmControls:pmListBox.Resources>
    <pmControls:pmListBox.ItemTemplate>
        <DataTemplate>
            <Button Command="{Binding Context.GetAllStatesCommand, Source={StaticResource dataContextBinder}" CommandParameter="{Binding}" [...] />                                           
        </DataTemplate>
    </pmControls:pmListBox.ItemTemplate>
</pmControls:pmListBox>
于 2012-11-08T12:54:19.597 回答