3

I have this listbox:

 <ListBox Name="lstEmployee" 
                 FontSize="32" 
                 SelectionChanged="lstEmployee_SelectionChanged" 
                 Margin="10,60,10,78" 
                 Grid.RowSpan="2"
                 Foreground="#FF3F575D">

and it is being filled this way:

 foreach (var contactdata in RootObject_1.results)
                {

                    StackPanel stk = new StackPanel();
                    stk.Name = "stack" + ctr.ToString();
                    stk.Orientation = System.Windows.Controls.Orientation.Vertical;
                    stk.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;

                    TextBlock txtBlk = new TextBlock();
                    txtBlk.Name = "txtBlk" + ctr.ToString();
                    txtBlk.Text = contactdata.name;
                    txtBlk.FontSize = 30;
                    txtBlk.FontWeight = System.Windows.FontWeights.Bold;
                    txtBlk.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    txtBlk.TextWrapping = TextWrapping.Wrap;

                    TextBlock txtBlk1 = new TextBlock();
                    txtBlk1.Name = "txtBlk" + ctr.ToString();
                    txtBlk1.Text = contactdata.formatted_address;
                    txtBlk1.FontSize = 22;
                    txtBlk1.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    txtBlk1.TextWrapping = TextWrapping.Wrap;

                    stk.Children.Add(txtBlk);  // index 0  
                    stk.Children.Add(txtBlk1);  // index 1  
                    lstEmployee.Items.Add(stk);

                    referenceList.Add(contactdata.reference.ToString());

                }

How can I change the selected item background with an image? ("\Image\Taxi\800\cellselect_800")

UPDATE

To make JSON Request I'm using this:

void chamaTaxi()
    {

        WebClient webClient = new WebClient();
        webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
        webClient.DownloadStringAsync(new Uri("https://maps.googleapis.com/maps/api/place/textsearch/json?&query=taxi&location=-19.94549444,-43.92314218&&radius=5000&sensor=true&key=AIzaSyDucC8QBV5wu4V-dQXFfABXGaaUzdmT5xw"));

    }
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
            Deployment.Current.Dispatcher.BeginInvoke(()=>
         {

                var RootObject_1 = JsonConvert.DeserializeObject<RootObject_1>(e.Result);

               **code above**
    }
}

For JSON classes I use this link:JSON URL and this generator: generator

Daniel Nazareth
  • 530
  • 1
  • 6
  • 22
  • I would suggest using a `DataTemplate` for you data rather than dynamicly creating the `ListBoxItem`, this way you could just bind you Results to the `listbox` and add the backgroun image. – sa_ddam213 Aug 13 '13 at 21:57
  • 1
    But using DataTemplate can I still fill the listbox dynamicly? Because the contactdata is coming from a json request, and the number of results may vary. – Daniel Nazareth Aug 13 '13 at 23:07
  • Yes, it will work with any amount of results, if you show what your `contactdata` class looks like I can show you an example. – sa_ddam213 Aug 13 '13 at 23:09
  • I was trying to put the code in comments, now it is in the question. – Daniel Nazareth Aug 13 '13 at 23:43
  • I have the same problem... Oo – Gavjr Sep 27 '13 at 17:55

2 Answers2

1

Here is a quick MVVM example of doing this using DataTemplate

Create a ObservableCollection to hold your data model and populate the list with your data and the DataTemplate will display the Data onscreen.

In the DataTemplate there is an Image that will be Visible only when the Item is selected

Xaml:

<Window x:Class="WpfApplication8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Name="UI">

    <Grid DataContext="{Binding ElementName=UI}" >
        <ListBox  ItemsSource="{Binding ContractDataList}" SelectedItem="{Binding SelectedItem}">
            <ListBox.Resources>
                <BooleanToVisibilityConverter x:Key="BoolToVisibleConverter" />
            </ListBox.Resources>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Image Source="Image\Taxi\800\cellselect_800.png" Stretch="Fill" Visibility="{Binding IsSelected, Converter={StaticResource BoolToVisibleConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}"/>
                        <StackPanel>
                            <TextBlock Text="{Binding Name}"/>
                            <TextBlock Text="{Binding Address}"/>
                        </StackPanel>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

Code:

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace WpfApplication8
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private ContractModel _selectedItem;
        private ObservableCollection<ContractModel> _contractDataList = new ObservableCollection<ContractModel>();

        public MainWindow()
        {
            InitializeComponent();

            //foreach (var contactdata in RootObject_1.results)
            for (int i = 0; i < 30; i++)
            {
                var model = new ContractModel
                {
                    Name = "name" + i,
                    Address = "address" + i,
                    Reference = i.ToString()
                };
                ContractDataList.Add(model);
            }
        }

        public ObservableCollection<ContractModel> ContractDataList
        {
            get { return _contractDataList; }
            set { _contractDataList = value; }
        }

        public ContractModel SelectedItem
        {
            get { return _selectedItem; }
            set { _selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
        }


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


    public class ContractModel : INotifyPropertyChanged
    {
        private string _name;
        private string _address;
        private string _reference;

        public string Name
        {
            get { return _name; }
            set { _name = value; NotifyPropertyChanged("Name"); }
        }

        public string Address
        {
            get { return _address; }
            set { _address = value; NotifyPropertyChanged("Address"); }
        }

        public string Reference
        {
            get { return _reference; }
            set { _reference = value; NotifyPropertyChanged("Reference"); }


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

Result: enter image description here

sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
0

I think you'd have to modify the ListBoxItem's control template. Three steps:

1) Locate the default control template for ListBoxItem -- should be found in this directory:

%ProgramFiles(x86)%\Windows Kits\8.0\Include\winrt\xaml\design

2) Insert your image into the control template (wherever you want it to appear), and hide it initially with opacity=0:

<Image x:Name="image" Source="Images/Taxi\800\cellselect_800" Opacity="0" />

3) Add an entry to the storyboard under VisualState x:Name="Selected". This will show the image when the item is selected:

<DoubleAnimation Storyboard.TargetName="image" Storyboard.TargetProperty="Opacity" Duration="0" To="1"/>
Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • I'm trying to edit it but is showing access denied message when I try to save it. – Daniel Nazareth Aug 13 '13 at 23:14
  • @DanielNazareth edit the file under `ProgramFiles` you mean? Don't do that -- copy the ` – McGarnagle Aug 13 '13 at 23:15
  • I copy this, and it is showing this messages in ContentPresenter: The member "ContentTransitions" is not recognized or is not accessible. The property 'ContentTransitions' was not found in type 'ContentPresenter'. You know why? – Daniel Nazareth Aug 14 '13 at 00:00
  • @DanielNazareth argh ... sorry, I'm not sure about that. If you post the code into your question, then I could take a look. (**Question**: the image is fixed, right? It doesn't change depending on the data? That was my assumption.) – McGarnagle Aug 14 '13 at 00:16