2010-12-21 6 views
7

MyObject 컬렉션을 표시하는 ListBox가 있습니다. 컬렉션은 ViewModel에 있습니다. ListItem의 버튼을 클릭하고 처리하려고하지만 바인딩과 관련하여 몇 가지 문제가 있습니다. 속성이 MyObject 속성에 바인딩되어 있으면 DataTemplate의 바인딩이 제대로 작동합니다. 하지만 ViewModel의 속성에 어떻게 바인딩 할 수 있습니까?ListBox의 Items에서 ViewModel의 속성에 바인딩을 사용하는 방법

클릭 이벤트를 처리하는 코드에서 항목의 정보를 어떻게 사용할 수 있습니까? 예를 들어, 항목의 TextBox에서 텍스트를 인쇄하고 싶습니다.

코드는 같다 :

<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 번호 : DataContext를 같은 당신이 어떤 AvatarClick RelayCommand이없는 거기에서 ObservableCollection에 개체에서 문자열 항목이있을 것이다

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의의의 . 바인딩에서 RelativeSource를 사용하여 부모 ListBox의 DataContext를 대신 사용할 수 있습니다. 두 번째 질문에 대한

, 당신은이

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) 
{ 
    //... 
} 
처럼 CommandParameter의 사용을 만들 수
관련 문제