1.데이터바인딩

바인딩 개체 만들기

namespace BusinessEntities
{
    public class Movies
    {
        public Movies(string Title) {

            this.Title = Title;
        
        }

        public string Title { set; get; }
    }
}

 

2.classMovies를 담을 ObservableCollection<BusinessEntities.Movies> 개체 생성

    public class AllMovies  :ObservableCollection<BusinessEntities.Movies>
    {
        public AllMovies() {

            this.Add(new BusinessEntities.Movies("제목"));
            this.Add(new BusinessEntities.Movies("제목"));
            this.Add(new BusinessEntities.Movies("제목"));
            this.Add(new BusinessEntities.Movies("제목"));
            this.Add(new BusinessEntities.Movies("제목"));

        }

        
    }

 

3.표시할 xaml (MovieList.xaml )만들기

   <ListBox x:Name="MyBooks" ItemsSource="{Binding Mode=OneWay}"  Margin="16,48,16,24" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" >
                      
                        <TextBlock Text="{Binding Title}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

 

4.바인딩하기 MovieList.xaml 비하인드 코드

	public partial class MovieList : UserControl
	{
        BusinessEntities.AllMovies am;
		public MovieList()
		{
			// 변수를 초기화하는 데 필요합니다.
			InitializeComponent();
            am = new BusinessEntities.AllMovies();
            MyBooks.DataContext = am;

		}




	}

 

------------------------------------------------------------------------------------------------

바인딩된 개체 알아내기

------------------------------------------------------------------------------------------------

이벤트 추가

<ListBox x:Name="MyBooks" ItemsSource="{Binding Mode=OneWay}"  Margin="16,48,16,24"   SelectionChanged="MyBooks_SelectionChanged">

비하인드 코드

//선택변경
private void MyBooks_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
     ListBox SelectMovies = sender as ListBox;
     BusinessEntities.Movies mv = SelectMovies.SelectedItem as BusinessEntities.Movies;
     MessageBox.Show(mv.Title); 

}

+ Recent posts