2010-12-21 79 views
7

我有一個ListBox顯示MyObjects的集合。該集合位於ViewModel中。我想處理一個ListItem上的按鈕的點擊,但有一些綁定的麻煩。如果該屬性綁定到MyObject屬性,則DataTemplate中的綁定工作正常。但是,我怎樣才能將它綁定到ViewModel的屬性?如何在列表框的項目中使用綁定到ViewModel的屬性

第二個問題我如何使用處理點擊事件的代碼中的項目信息。例如,我想打印出項目文本框中的文本。

的代碼是這樣的:

<Window.Resources> 
    <DataTemplate x:Key="ItemTemplate"> 
     <Button Content="{Binding .}" 
       Command="{Binding ClickCommand}" /> <!--It doesn't work--> 
    </DataTemplate> 

</Window.Resources> 
<ListBox x:Name="ListBox" 
     ItemsSource="{Binding Path=Objects}" 
     IsSynchronizedWithCurrentItem="True" 
     ItemTemplate="{StaticResource ItemTemplate}"/> 

C#:

public partial class MainWindow : Window 
{ 
    VM m_vm; 

    public MainWindow() 
    { 
     m_vm = new VM(); 
     this.DataContext = m_vm; 
     InitializeComponent(); 
    } 
} 

public class VM 
{ 
    ObservableCollection<string> _objects; 

    public ObservableCollection<string> Objects 
    { 
     get { return _objects; } 
     set { _objects = value; } 
    } 

    public VM() 
    { 
     _objects = new ObservableCollection<string>(); 
     Objects.Add("A"); 
     Objects.Add("B"); 
     Objects.Add("C"); 
    } 

    //I used relayCommand from the John Smith articles 
    RelayCommand _clickCommand; 
    public ICommand ClickCommand 
    { 
     get 
     { 
      if (_clickCommand == null) 
      { 
       _clickCommand = new RelayCommand(() => this.AvatarClick()); 
      } 
      return _clickCommand; 
     } 
    } 

    public void AvatarClick() 
    { 
     //how to get here the text from the particular item where the button was clicked? 
    } 
} 

回答

11

你ListBoxItem的公司將不得不從的ObservableCollection對象的DataContext的,並從那裏你沒有任何AvatarClick RelayCommand串項目。您可以使用Binding中的RelativeSource來代替使用父級ListBox中的DataContext。

關於第二個問題,你可以利用CommandParameter像這樣

的XAML

<DataTemplate x:Key="ItemTemplate"> 
    <Button Content="{Binding .}" 
      Command="{Binding DataContext.ClickCommand, 
           RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" 
      CommandParameter="{Binding .}"/> 
</DataTemplate> 

視圖模型

public ICommand ClickCommand 
{ 
    get 
    { 
     if (_clickCommand == null) 
     { 
      _clickCommand = new RelayCommand(param => this.AvatarClick(param)); 
     } 
     return _clickCommand; 
    } 
} 

public void AvatarClick(object param) 
{ 
    //... 
} 
相關問題