2011-07-11 38 views
0

我有一個問題,我創建了一個ListBoxItem在extression混合,它有一個StackPanel,這包含一個ImageTextBlock如何在表達式混合中使用ListBoxItems?

問題是,我不知道如何設置屬性來訪問圖像和文本塊來設置它。 我可以創建新的項目,但如何設置圖像的網址和文本?

+0

如果您可以提供XAML和您正在綁定的數據結構,將能夠提供更好的幫助。 – kanchirk

回答

1

XAML需要綁定到數據源中的屬性,並且需要設置ListBox的ItemsSource。我在xaml和.cs下面包含了生成所示屏幕快照的信息。我還包含了一個包含數據的簡單類。

 <ListBox x:Name="myItems"> 
      <ListBox.ItemTemplate> 
       <DataTemplate > 
        <StackPanel Orientation="Horizontal"> 
         <Image Source="{Binding image}" Margin="5" /> 
         <TextBlock Text="{Binding myName}" VerticalAlignment="Center" /> 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

的的的MainPage的.cs應包括:

public partial class MainPage : PhoneApplicationPage 
{ 
    ObservableCollection<dataItem> items; 

    public MainPage() 
    { 
     InitializeComponent(); 
     items = new ObservableCollection<dataItem>(); 
     addItems(); 
     this.myItems.ItemsSource = items; 
    } 

    private void addItems() 
    { 
     items.Add(new dataItem() { myName = "Jason", image = "1.png" }); 
     items.Add(new dataItem() { myName = "Joanne", image = "2.png" }); 
    } 
} 

我的數據對象被稱爲DataItem的,看起來像這樣:

public class dataItem : INotifyPropertyChanged 
{ 

    private string _name = ""; 
    public string myName 
    { 
     get 
     { 
      return _name; 
     } 
     set 
     { 
      if (value != _name) 
      { 
       _name = value; 
       NotifyPropertyChanged("myName"); 
      } 
     } 
    } 

    private string _image = ""; 
    public string image 
    { 
     get 
     { 
      return _image; 
     } 
     set 
     { 
      if (_image != value) 
       _image = value; 
      NotifyPropertyChanged("image"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    public void NotifyPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

我已經實現INotifyPropertyChanged的,以確保UI在新項目被添加到數據源(dataItem)時被更新。圖像需要添加爲內容,應該是複製總是,以確保它們在設備上。完成後的應用程序是這樣的:

Phone screen grab

我希望這有助於。

Jason。