2011-10-27 9 views
1

リストにバインドされているオブジェクトUserNamesにはどうすればアクセスできますか?リストのリスト項目のボタンを識別する方法

項目は、私の場合にはオブジェクトです::

new List<UserNames>(); 
this.users.Add(new UserNames() {Id = 1, UserName = "name 1"}); 

私はラベルやボタンを持っているデータテンプレートを使用しています私は、これまでになかった何

。次のように

私のリストです:

<ListBox Grid.Column="1" Grid.Row="1" Name="listBox1" ItemsSource="{Binding}" SelectedValuePath="Id"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <WrapPanel Orientation="Vertical"> 
         <StackPanel> 
          <Label Content="{Binding UserName}" /> 
         </StackPanel> 
         <StackPanel Name="ButtonStackPanel"> 
          <Button Name="MyButton" Content="Click Me" Click="MyButton_Click"> 

          </Button> 
         </StackPanel> 
        </WrapPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

ボタンのための私の方法である場合。あなたは私が親オプションを利用しようとしますが、XAMLで成功事例の

private void MyButton_Click(object sender, RoutedEventArgs e) 
     { 
      //StackPanel panel = (StackPanel)((Button)sender).Parent; 
      //WrapPanel wrapPanel = (WrapPanel) panel.Parent; 
      //ListItem listItem = (ListItem) wrapPanel.Parent; 
      //ListBox box = (ListBox) listItem.Parent; 
      //UserNames itemToReport = (UserNames) (box.SelectedItem); 
      //MessageBox.Show(itemToReport.UserName); 


     } 

答えて

1

それは私がいつも思って

private void MyButton_Click(object sender, RoutedEventArgs e) 
{ 
    Button b = sender as Button; 
    UserNames data = b.DataContext as UserNames; 

    MessageBox.Show(data.UserName); 
} 

あなたUserName対象となりますので、あなたは、ボタンのDataContextを使用することができますWPFと、アプリケーションのことDataContextですが、Buttons、ListBoxes、TextBoxesなどのUIオブジェクトは、ユーザーがそれを操作できるように、DataContextの上に置かれた単純なレイヤーです。

+0

これは、限り、我々はbussinesslayerクラスにUI要素をバックキャストする必要があることを受け入れるように正しいです。しかし、より良い答えは、2つを完全に切り離す方法を指摘することです。たとえば、Q:http://stackoverflow.com/questions/1384369/mvvm-binding-to-listbox-selecteditemを参照してください。 – Dabblernl

+0

これは私が必要としていたものです。私はあなたのソリューションがシンプルだが好きだが、それは素晴らしい説明だ。ありがとうございました – cpoDesign

+0

@Dabblernlはい、私はViewModelにRelayCommandを使用する完全な例を書こうと思っていましたが、OPはWPFに新しくなっているようですので、私は彼を怖がらないでしょう:) – Rachel

1

なしでした見ることができるように、現在の項目にTagプロパティを設定します。

クリックハンドラでは、それを元に戻します。

ユーザー名user =(送信者としてのボタン).Tagをユーザー名として使用します。

0

データのバインドをバインドするには、ObservableCollectionを使用するのが最も簡単です(データがランタイムを変更している場合)。バインディングを行うときは、datacontext、datasoure、およびdatapathを定義する必要があります。私は、MSDNに結合について、いくつかの続きを読むにはあなたをアドバイスします:D

0

これはあなたのために動作します -

MessageBox.Show(((sender as Button).DataContext as UserNames).UserName); 
関連する問題