2010-12-21 72 views
7

Tôi có một ListBox hiển thị bộ sưu tập MyObjects. Bộ sưu tập nằm trong ViewModel. Tôi muốn xử lý một nhấp chuột vào nút trên ListItem nhưng có một số khó khăn với ràng buộc. Ràng buộc trong DataTemplate hoạt động tốt nếu thuộc tính được liên kết với thuộc tính MyObject. Nhưng làm thế nào tôi có thể liên kết nó với tài sản từ ViewModel?Cách sử dụng liên kết trong các Mục của ListBox với các thuộc tính của ViewModel

Câu hỏi thứ hai là cách tôi có thể sử dụng thông tin từ mục trong mã xử lý sự kiện nhấp chuột. Ví dụ: tôi muốn in văn bản từ Hộp văn bản của mục.

Mã này là như thế:

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

Trả lời

11

ListBoxItem của bạn sẽ có các mục chuỗi từ các đối tượng ObservableCollection như DataContext và từ đó bạn không có bất kỳ AvatarClick RelayCommand . Bạn có thể sử dụng RelativeSource trong Binding để sử dụng DataContext từ ListBox cha mẹ thay thế.

Đối với câu hỏi thứ hai của bạn, bạn có thể tận dụng các CommandParameter như thế này

XAML

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

ViewModel

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

public void AvatarClick(object param) 
{ 
    //... 
} 
Các vấn đề liên quan