2012-03-12 10 views
0

나는 WP7 및 C#의 신입생이며 목록 상자 제거와 혼동합니다. 클릭 이벤트 (항목 데이터 제거 및 UI 새로 고침)를 통해 항목을 제거하고 싶습니다. 웹 사이트에서 검색했으며, 첫 번째 자원은 ObservableCollection을 확장해야한다는 것을 알았지 만 다음 단계는 무엇입니까? 누가 더 자세한 예제를 제공 할 수 있습니까? 내 코드 MainPage.xaml입니다. Example source downloadWP7의 목록 상자에서 항목 제거

<phone:PhoneApplicationPage x:Class="WPListBoxImage.MainPage" 
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
          xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
          xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
          xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
          xmlns:data="clr-namespace:WPListBoxImage" 
          mc:Ignorable="d" 
          d:DesignWidth="480" 
          d:DesignHeight="768" 
          FontFamily="{StaticResource PhoneFontFamilyNormal}" 
          FontSize="{StaticResource PhoneFontSizeNormal}" 
          Foreground="{StaticResource PhoneForegroundBrush}" 
          SupportedOrientations="Portrait" 
          Orientation="Portrait" 
          shell:SystemTray.IsVisible="True"> 
    <phone:PhoneApplicationPage.Resources> 
    <data:Products x:Key="productCollection" /> 
    <data:PriceConverter x:Key="priceConvert" /> 
    </phone:PhoneApplicationPage.Resources> 
    <!--LayoutRoot is the root grid where all page content is placed--> 
    <Grid x:Name="LayoutRoot" 
     Background="Transparent"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto" /> 
     <RowDefinition Height="*" /> 
    </Grid.RowDefinitions> 
    <!--TitlePanel contains the name of the application and page title--> 
    <StackPanel x:Name="TitlePanel" 
       Grid.Row="0" 
       Margin="12,17,0,28"> 
     <TextBlock x:Name="ApplicationTitle" 
       Text="PDSA" 
       Style="{StaticResource PhoneTextNormalStyle}" /> 
     <TextBlock x:Name="PageTitle" 
       Text="Products" 
       Margin="9,-7,0,0" 
       Style="{StaticResource PhoneTextTitle1Style}" /> 
    </StackPanel> 
    <!--ContentPanel - place additional content here--> 
    <Grid x:Name="ContentPanel" 
      Grid.Row="1" 
      Margin="12,0,12,0"> 
     <ListBox x:Name="lstData" 
       ItemsSource="{Binding Source={StaticResource productCollection}, Path=DataCollection}" SelectionChanged="lstData_SelectionChanged"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <Image Margin="8" 
        VerticalAlignment="Top" 
        Source="{Binding Path=ImageUri}" 
        Width="100" 
        Height="100" /> 
       <StackPanel> 
       <TextBlock Margin="8" 
          Width="250" 
          TextWrapping="Wrap" 
          VerticalAlignment="Top" 
          HorizontalAlignment="Left" 
          Text="{Binding Path=ProductName}" /> 
       <TextBlock Width="100" 
          Margin="8,0,8,8" 
          VerticalAlignment="Top" 
          HorizontalAlignment="Left" 
          Text="{Binding Path=Price, Converter={StaticResource priceConvert}}" /> 
       </StackPanel> 
      </StackPanel> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
     </ListBox> 
    </Grid> 
    </Grid> 
</phone:PhoneApplicationPage> 

MainPage.xaml.cs를

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 
using Microsoft.Phone.Controls; 

namespace WPListBoxImage 
{ 
    public partial class MainPage : PhoneApplicationPage 
    { 
    // Constructor 
    public MainPage() 
    { 
     InitializeComponent(); 
    } 

    private void lstData_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 

     ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem); 
     //delete a item,what should to do next? 
    } 
    } 
} 

Products.cs

using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 
using System.Linq; 

namespace WPListBoxImage 
{ 
    //a ObservableCollection<T>, 
    public class Products : ObservableCollection<Product> 
    { 
    public Products() 
    { 
     DataCollection = new ObservableCollection<Product>(); 
     BuildCollection(); 
    } 

    private const string IMG_PATH = "../Images/"; 

    public ObservableCollection<Product> DataCollection { get; set; } 

    public ObservableCollection<Product> BuildCollection() 
    { 
     //DataCollection = new ObservableCollection<Product>(); 

     DataCollection.Add(new Product("Haystack Code Generator for .NET", 799, IMG_PATH + "Haystack.jpg")); 
     DataCollection.Add(new Product("Fundamentals of N-Tier eBook", Convert.ToDecimal(19.95), IMG_PATH + "FundNTier_100.jpg")); 
     DataCollection.Add(new Product("Fundamentals of ASP.NET Security eBook", Convert.ToDecimal(19.95), IMG_PATH + "FundSecurity_100.jpg")); 
     DataCollection.Add(new Product("Fundamentals of SQL Server eBook", Convert.ToDecimal(19.95), IMG_PATH + "FundSQL_100.jpg")); 
     DataCollection.Add(new Product("Fundamentals of VB.NET eBook", Convert.ToDecimal(19.95), IMG_PATH + "FundVBNet_100.jpg")); 
     DataCollection.Add(new Product("Fundamentals of .NET eBook", Convert.ToDecimal(19.95), IMG_PATH + "FundDotNet_100.jpg")); 
     DataCollection.Add(new Product("Architecting ASP.NET eBook", Convert.ToDecimal(19.95), IMG_PATH + "ArchASPNET_100.jpg")); 
     DataCollection.Add(new Product("PDSA .NET Productivity Framework", Convert.ToDecimal(2500), IMG_PATH + "framework.jpg")); 

     return DataCollection; 
    } 

    } 
} 

Product.cs

using System; 

namespace WPListBoxImage 
{ 
    public class Product 
    { 
    #region Constructors 

    public Product() 
    { 
    } 

    public Product(string name, decimal price, string imageUri) 
    { 
     this.ProductName = name; 
     this.Price = price; 
     this.ImageUri = imageUri; 
    } 
    #endregion 

    public string ProductName { get; set; } 
    public decimal Price { get; set; } 
    public string ImageUri { get; set; } 
    } 
} 

여기에 응용 프로그램의 스크린 샷입니다. enter image description here

양해 해 주셔서 감사합니다.

+0

addtional : 첫째, 라인에서'ListBoxItem의 LBI = ((리스트 박스로 보낸 ListBoxItem의 등) .SelectedItem)', 왜 변환을 둘째, 사실, productCollection은 먼저 변환해야하는 ObservableCollection이 아닙니다 .'myData = productCollection.DataCollection;'그런 다음,'ProductData'는' UI를 업데이트하려면 myData.Remove (lbi); –

답변

2

제품 클래스는 아무것도 상속하지 않아야합니다.

public class Products 

컬렉션의 모든 항목에 액세스하는 것은 Product 클래스의 DataCollection 속성을 통해 수행됩니다. 예 :

Products myProducts = new Products(); 
    ObservableCollection<Product> myData = myProducts.DataCollection; 

또한 제품 사용 방법에 따라 다릅니다. 당신은 완전히이 클래스 멀리 할 수있을 다음과 같이 할 수 있습니다

ObservableCollection<Product> Products = new ObservableCollection<Product>(); 
    Products.Add(new Product("Haystack Code Generator for .NET", 799, IMG_PATH + "Haystack.jpg")); 
    // etc... 
1

은 첫째로 당신의 제품 컬렉션에 대한 참조를 취득해야합니다

Products productCollection = this.Resources["productCollection"] as Products; 

그런 다음, 이것은 ListBoxItemDataContext 될 것입니다 클릭 된 항목을 찾을 수 :

ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem); 
Product product = lbi.DataContext as Product; 

을 (비록, I Product 인스턴스가되어야한다고 생각하면은 귀하의 목록 상자가 데이터 바인딩되어 있다고 생각합니다. N

그럼 간단하게 제거) 디버거이 자신을 확인하십시오 ObservableCollection는 UI가 업데이트되어 있는지 확인합니다 :

productCollection.Remove(product); 
+0

줄'((ListBox로 보낸 사람). ListBoxItem으로 .SelectedItem);'반환 null, 변환 오류. 어떻게 고칠 수 있습니까? –

+0

내 대답을 읽었습니까? "귀하의 목록 상자가 데이터 바인딩 된 것으로 생각되면 SelectedItem이 Product 인스턴스 여야한다고 생각합니다." – ColinE

+0

나는 틀림없이 왜 틀림없이 ListBoxItem으로 ListBoxItem이 왜 틀렸는 지 생각합니다. 목록 상자 사이에 어떤 관계가 databound입니까?죄송합니다, 저는 정말 새롭습니다 –

관련 문제