2012-11-08 24 views
2

我正在使用Listbox,它包含按鈕,並且我想使用command.but我的命令處理按鈕單擊事件。如何在Silverlight4中的列表框中調用命令

是這樣正確嗎?

<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> 

回答

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> 
+0

感謝它的作品,但現在我的命令調用,但又失去了我給列表框的先前綁定:ItemsSource =「{Binding Countries}」SelectedItem =「{Binding SelectedCountry}」,我沒有得到選擇對象? – Gayatri

+0

請參閱我的修改答案 - 如果綁定了ID,您當然只會將該項目作爲命令參數。無論你在代碼中找到''[...]'我給你留下了一些提高可讀性的東西...... – Spontifixus