2010-12-21 6 views
7

MyObjectのコレクションを表示するListBoxがあります。コレクションはViewModelにあります。私はListItemのボタンをクリックして処理したいが、バインディングにはいくつか問題がある。プロパティがMyObjectプロパティにバインドされている場合、DataTemplateのバインドは正常に機能します。しかし、それをViewModelからプロパティにバインドするにはどうすればよいですか?ListBoxの項目でViewModelのプロパティにバインディングを使用する方法

クリックイベントを処理するコード内の項目の情報をどのように使用できるのかという2番目の質問です。たとえば、アイテムの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#:

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さんはDataContextのようのObservableCollectionオブジェクトから文字列の項目がありますし、そこから、あなたはどんなAvatarClick RelayCommandを持っていません。バインディングでRelativeSourceを使用すると、代わりに親のListBoxからDataContextを使用できます。あなたの2番目の質問については

、あなたがこの

ようCommandParameterの使用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) 
{ 
    //... 
} 
を作ることができます
関連する問題