我在每个listboxItem里都加了一个按钮,点击按钮后,如何知道点击的按钮是属于哪个item呢?谢谢~~

解决方案 »

  1.   

    高手么,可否说的详情点儿?
    item.owner里的item是指listbox的item吗?
    parent我试过了,不行。
    绑定datacontext 或者tag 具体要怎么做呢?
      

  2.   

    写个datatemplate,然后再写个model存放你的数据,例如显示的东西,button上面的文字等,一个model对应的就是一个item,点击按钮时,按钮的datacontext就是那个model
      

  3.   

    using System.Collections.ObjectModel;
    using System.Windows;namespace TestMultiLines
    {
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1
        {
            public Window1()
            {
                InitializeComponent();
            }        private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                ObservableCollection<TestModel> test = new ObservableCollection<TestModel>();
                test.Add(new TestModel {test = "1"});
                test.Add(new TestModel {test = "2"});
                test.Add(new TestModel {test = "3"});
                test.Add(new TestModel {test = "4"});
                test.Add(new TestModel {test = "5"});
                listView.DataContext = test;
            }        private void Button_Click(object sender, RoutedEventArgs e)
            {
                MessageBox.Show(sender.ToString());
            }
        }    class TestModel : DependencyObject
        {
            public string test
            {
                get { return (string)GetValue(testProperty); }
                set { SetValue(testProperty, value); }
            }        public static DependencyProperty testProperty = DependencyProperty.Register("test", typeof(string),
                                                                                        typeof(TestModel));
        }
    }
      

  4.   

    <Window x:Class="TestMultiLines.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="Window_Loaded"
        Title="Window1" Height="300" Width="300">
        <Window.Resources>
            <DataTemplate x:Key="testTemplate">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=test}" />
                    <Button Content="{Binding Path=test}" Click="Button_Click" />
                </StackPanel>
            </DataTemplate>
        </Window.Resources>
        <Grid>
            <ListView Name="listView" ItemTemplate="{StaticResource testTemplate}" ItemsSource="{Binding}" />
        </Grid>
    </Window>
      

  5.   

    楼上的方法只适用与很简单的数据结构。
    点击按钮后,sender的类型也只是一个Button,而不是TestModel,
    我想得到按钮对应的TestModel 。
      

  6.   

    sender是个button,你看看(sender as Button).DataContext是什么,这个方法应该适用于任何数据结构,界面的呈现Model可以定义的很复杂的
      

  7.   

    关键点是这句:
    (sender as Button).DataContext明白了,非常感谢!!