如何使用表达式混合中的ListBox项?

时间:2011-07-11 14:32:04

标签: windows-phone-7

我有一个问题,我在Extression blend中创建了一个ListBoxItem,它有StackPanel,其中包含ImageTextBlock

问题是,我不知道如何设置属性来访问图像和文本块来设置它。 我可以创建新项目,但如何设置图像网址和文字?

1 个答案:

答案 0 :(得分: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以确保在将新项添加到数据源(dataItem)时更新UI。图片需要添加为内容,并且应始终复制以确保它们在设备上。完成的应用程序看起来像:

Phone screen grab

我希望这会有所帮助。

杰森。