2010-12-21 28 views
7

Tengo un ListBox que muestra la colección de MyObjects. La colección está en ViewModel. Quiero manejar un clic en el botón en el ListItem pero tengo algunos problemas con el enlace. El enlace en DataTemplate funciona bien si la propiedad está vinculada a la propiedad MyObject. Pero, ¿cómo puedo vincularlo a la propiedad desde ViewModel?Cómo utilizar el enlace en los elementos del ListBox a las propiedades del ViewModel

La segunda pregunta es cómo puedo usar la información del elemento en el código que maneja el evento de clic. Por ejemplo, quiero imprimir el texto del TextBox del artículo.

El código es así:

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

Respuesta

11

Sus ListBoxItem de que tenga las opciones de cadena de los objetos ObservableCollection como DataContext y desde allí no tiene ninguna RelayCommand AvatarClick . Puede usar RelativeSource en la vinculación para usar el DataContext del ListBox padre en su lugar.

a su segunda pregunta, se puede hacer uso de la CommandParameter como esto

Xaml

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

modelo de vista

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

public void AvatarClick(object param) 
{ 
    //... 
} 
Cuestiones relacionadas