2009-12-24 2 views
3

원하는 기능은 목록 상자의 각 항목 옆에있는 제거 단추를 사용하여 사용자가 클릭 할 때 해당 특정 항목이 목록에서 제거되도록하는 것입니다.Silverlight : 목록 상자에 대한 datatemplate의 이벤트

나는 그것을 데이터 템플릿에 넣을 생각을하고 있지만 그걸로 어떻게 연결시킬 것인가?

감사 ObservableCollection에 귀하의 목록 상자의 숀 맥클린

답변

2

다음은이 문제에 접근하는 한 가지 방법입니다. ObservableCollection을 만들고 ItemsSource를 해당 Collection과 동일하게 설정하십시오. 그런 다음 버튼 클릭 처리기는 항목을 제거 할 수 있습니다. 이 샘플에서

using System; 
using System.Collections.ObjectModel; 
using System.Windows.Controls; 

namespace SilverlightApplication1 
{ 
    public partial class MainPage : UserControl 
    { 
     private ObservableCollection<string> _customers; 

     public MainPage() 
     { 
      InitializeComponent(); 

      _customers = new ObservableCollection<string>() { "Bob", "Mark", "Steve" }; 
      this.DataContext = _customers; 
     } 

     public void remove_Click(object sender, EventArgs e) 
     { 
      var button = sender as Button; 
      if (button == null) 
       return; 

      var name = button.DataContext as string; 
      if (string.IsNullOrEmpty(name)) 
       return; 

      _customers.Remove(name); 
     } 
    } 
} 

당신의 XAML은 다음과 같이 보일 것이다 :

<Grid x:Name="LayoutRoot"> 
    <ListBox ItemsSource="{Binding}"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal" > 
        <TextBlock Text="{Binding}" /> 
        <Button Content="Remove" Click="remove_Click" /> 
       </StackPanel> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</Grid> 
1

바인딩 ItemsSource. 삭제 버튼을 데이터 템플릿에 넣습니다.

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    var button = sender as Button; 
    if (button != null) 
    { 
     var yourObject = button.DataContext as YourObject; 
     if (yourObject != null) 
     { 
      YourObjectsObservableCollection.Remove(yourObject); 
     } 
    } 
} 

그래서 당신이 버튼의 DataContext에서 ListBoxItem의 바인딩 된 개체를 검색 할 수있는 버튼에 대한 Click 이벤트 처리기는 다음과 같이 할 수 있습니다.

관련 문제