Is it possible to bind an Event in a Silverlight DataTemplate?

后端 未结 2 506
傲寒
傲寒 2021-02-08 00:44

Is it possible to bind an Event in a Silverlight DataTemplate? If so, what is the best way to do it?

For example, say you\'ve created a DataTemplate that has a Button in

2条回答
  •  甜味超标
    2021-02-08 01:11

    There are a couple of options.

    One. make a custom control that is bound the data object for that row. On that custom control add the handler for the bound object.

    I dont think your binding on the click will work. Sans the Binding Statment and just declare your click to a string.

    Add the handler on the page where the control is housed. Keep in mind that if you bind this way you will only be able to work with the sender of that item (button) and it's properties. If you need to get at specific attributes on an object you maybe better off pursuing the first option.

    Small Example demonstrating the functionality by adding 10 buttons to a list box with click events. HTH

    DataTemplate XAML

    
        
            
                

    ListBox XAML

    
    

    Code Behind (I just plugged this all into the page.xaml file

    public class MyClass
    {
        public string ItemText { get; set; }
    }
    
    
    public partial class Page : UserControl
    {
        ObservableCollection _Items;
        public Page()
        {
            InitializeComponent();
    
            _Items = new ObservableCollection();
    
            for (int i = 0; i < 10; i++)
            {
                _Items.Add(new MyClass() {ItemText= string.Format("Item - {0}", i)});
            }
    
            this.ListBoxThingee.ItemsSource = _Items;
        }
    
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button _b = sender as Button;
            if (_b != null)
            {
                string _s = _b.Content as string;
                MessageBox.Show(_s);
            }
    
        }
    }
    

提交回复
热议问题