开发者

howto work with ListBoxItems in expression blend?

i have a question, i have created a ListBoxItem in extression blend, which has a StackPanel and this contains a Image and TextBlock.

the problem is, that i dont know ho开发者_C百科w to set a property to get access to the image and textblock to set it. i can create new item but how to set the image url and text?


The XAML needs to bind to the properties in the datasource, and the ItemsSource of the ListBox needs to be set. I include below the xaml and .cs that generates the screen shot shown. I have also included a simple class that contains the data.

        <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>

The .cs for the MainPage should include:

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" });
    }
}

My data object is called dataItem and looks like so:

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));
        }
    }
}

I have implemented INotifyPropertyChanged to ensure that the UI is updated as new items are added to the datasource (dataItem). The images need to be added as content and should be Copy Always to ensure they are on the device. The finished app looks like:

howto work with ListBoxItems in expression blend?

I hope this helps.

Jason.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜