I am trying to add an object to an ObservableCollection. As mentioned in a few question on this very site, I even tried to instantiate the collection before adding item. However, I am still getting the error. Here is my observation collection:
//Datacontext for local database
private WordDataContext wordsDB;
//Observable collection for binding
private ObservableCollection<WordItem> _wordItems = new ObservableCollection<WordItem>();
public ObservableCollection<WordItem> WordItems
{
get
{
return _wordItems;
}
set
{
if (_wordItems != value)
{
_wordItems = value;
NotifyPropertyChanged("WordItems");
}
}
}
I have overridden onNavigatedTo
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
// Define the query to gather all of the idea items.
var wordItemsInDB = from WordItem word in wordsDB.WordItems
select word;
// Execute the query and place the results into a collection.
WordItems = new ObservableCollection<WordItem>(wordItemsInDB);
// Call the base method.
base.OnNavigatedTo(e);
}
And here is the button to add new item
private void newIdeaAddButton_Click(object sender, RoutedEventArgs e)
{
//// Create a new idea item based on the text box.
//WordItem newIdea = new WordItem { WordName = "TestTest" };
//Debug.WriteLine("I'm here!");
//// Add a idea item to the observable collection.
//WordItems.Add(newIdea);
//// Add a idea item to the local database.
//wordsDB.WordItems.InsertOnSubmit(newIdea);
WordItem newword = new WordItem { WordName = "Bingo" };
if (WordItems == null)
{
Debug.WriteLine("I'm null!");
WordItems = new ObservableCollection<WordItem>();
}
WordItems.Add(newword);
wordsDB.WordItems.InsertOnSubmit(newword);
Debug.WriteLine("Did something!");
}
And here's the XAML
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<!--<ListBox Margin="14,0,-12,0" FontSize="{StaticResource PhoneFontSizeExtraLarge}" FontFamily="{StaticResource PhoneFontFamilySemiLight}">
<ListBoxItem Content="About" Tap="GoToAbout"/>
</ListBox>-->
<telerikData:RadJumpList x:Name="TestList" IsStickyHeaderEnabled="True" Margin="14,0,-12,0" ItemsSource="{Binding WordItems}">
<telerikData:RadJumpList.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="74">
<Rectangle x:Name="Bully" Width="20" Fill="Gray" Height="62" VerticalAlignment="Top" HorizontalAlignment="Left" />
<TextBlock Style="{StaticResource PhoneTextExtraLargeStyle}" Text="{Binding WordItem}" VerticalAlignment="Top"/>
</StackPanel>
</DataTemplate>
</telerikData:RadJumpList.ItemTemplate>
<telerikData:RadJumpList.StickyHeaderTemplate>
<DataTemplate>
<Border HorizontalAlignment="Stretch" Background="{StaticResource PhoneBackgroundBrush}" Height="74">
<Border Background="{StaticResource PhoneAccentBrush}" VerticalAlignment="Top" HorizontalAlignment="Left" Width="62" Height="62">
<TextBlock Text="{Binding}" FontFamily="{StaticResource PhoneFontFamilySemiLight}" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Padding="7,0,0,0" VerticalAlignment="Bottom" Foreground="White" />
</Border>
</Border>
</DataTemplate>
</telerikData:RadJumpList.StickyHeaderTemplate>
<telerikData:RadJumpList.GroupHeaderTemplate>
<DataTemplate>
<Border HorizontalAlignment="Stretch" Background="{StaticResource PhoneBackgroundBrush}" Height="74">
<Border Background="{StaticResource PhoneAccentBrush}" VerticalAlignment="Top" HorizontalAlignment="Left" Width="62" Height="62">
<TextBlock Text="{Binding}" FontFamily="{StaticResource PhoneFontFamilySemiLight}" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Padding="7,0,0,0" VerticalAlignment="Bottom" Foreground="White" />
</Border>
</Border>
</DataTemplate>
</telerikData:RadJumpList.GroupHeaderTemplate>
<telerikData:RadJumpList.GroupPickerItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel HorizontalAlignment="Center" ItemHeight="111" ItemWidth="111"/>
</ItemsPanelTemplate>
</telerikData:RadJumpList.GroupPickerItemsPanel>
<telerikData:RadJumpList.GroupPickerItemTemplate>
<DataTemplate>
<Border Background="{StaticResource PhoneAccentBrush}" Width="99" Height="99" VerticalAlignment="Top" HorizontalAlignment="Left">
<TextBlock Text="{Binding}" Style="{StaticResource PhoneTextExtraLargeStyle}" VerticalAlignment="Bottom" Foreground="White" />
</Border>
</DataTemplate>
</telerikData:RadJumpList.GroupPickerItemTemplate>
</telerikData:RadJumpList>
<Button x:Name="newIdeaAddButton" Click="newIdeaAddButton_Click" Content="Button" Height="72" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="160" />
</Grid>
Okay, I finally got the solution! The problem in itself is a bit obscure. The thing is that, earlier, I had RadJumplist bound to a List<strings> and it had GroupDescriptor defined accordingly
GenericGroupDescriptor<string, string> testgroup = new GenericGroupDescriptor<string, string>(listitem => listitem.Substring(0, 1).ToLower());
However, the scenario in question is about ObservableCollection<WordItem>. As soon as an item is added to the collection, the RadJumpList is notified about those changes and the GroupDescriptor proves to be invalid in that context. That somehow raises the NullReferenceException. It's a bit unintuitive to relate the error with the cause.
So, the simple solution was to change the descriptor as follows
GenericGroupDescriptor<WordItem, string> gengd = new GenericGroupDescriptor<WordItem, string>();
gengd.KeySelector = (WordItem item) =>
{
char keyhead = item.WordName[0];
return keyhead.ToString().ToLower();
};
This thing is not really well documented!
Related
I have a ListBox including an ItemTemplate with a StackPanel. I want to access that stackpanel and change its visibility.
(Change it's visibility to collapsed when I click mouseleftbutton "closeAll")
I can do that with FindDescendantByName Method but it works for only listbox items on screen (Only first 10 items) but when I am scrolling down, I see that this is not working for other listbox items.
I think that errors occurs because of VisualTreeHelper. What can I use instead of VisualTreeHelper?
Thanks..
XAML CODE
<ListBox x:Name="listBoxEditPast" SelectionMode="Single" Margin="0" Background="#272B34" ScrollViewer.VerticalScrollBarVisibility="Visible">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border Grid.Row="0" BorderThickness="4,0,0,0" Margin="2,0,0,0" Height="29" Background="#2E323B" Width="1050" BorderBrush="#1373A9" MouseLeftButtonDown="Border_MouseLeftButtonDown">
<DockPanel Name="dockPanelPast" Margin="0,4,0,0">
<Image Name="imgArrow" Source="images/down-arrow.png" HorizontalAlignment="Left" Width="20" Height="18"/>
<TextBlock Text="{Binding CreateDate}" Name="txtTarih" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="16"/>
<TextBlock Text="{Binding SarjNo}" Name="txtSarjNo" Foreground="#FF9CA518" HorizontalAlignment="Stretch" VerticalAlignment="Center" FontSize="16" Margin="50,0,0,0" Width="90"/>
<TextBlock Text="{Binding Adi}" Name="txtReceteAdi" Foreground="#FF26A053" VerticalAlignment="Center" FontSize="16" Margin="40,0,0,0" HorizontalAlignment="Stretch"/>
<Button Content="Detaylar" Style="{StaticResource BlueButton}" HorizontalAlignment="Right" VerticalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" DockPanel.Dock="Right"/>
</DockPanel>
</Border>
<StackPanel Grid.Row="1" Name="stackPanelDetay" Tag="{Binding ID}">
<DockPanel>
<TextBlock Text="Sipariş No" Foreground="#D9480F" VerticalAlignment="Center" />
<TextBlock Text="Parça" Foreground="#AF0FD9" VerticalAlignment="Center" Margin="50,0,0,0" Width="200" />
<TextBlock Text="Malzeme" Foreground="White" VerticalAlignment="Center" Margin="150,0,0,0" Width="90"/>
<TextBlock Text="Müşteri" Foreground="#AF0FD9" VerticalAlignment="Center" Margin="70,0,0,0" />
</DockPanel>
<DockPanel>
<TextBlock Text="{Binding ID}" Foreground="White" VerticalAlignment="Center" Width="100"/>
<TextBlock Text="{Binding ParcaKoduAdi}" Foreground="White" VerticalAlignment="Center" Margin="5,0,0,0" Width="200" />
<TextBlock Text="{Binding Malzeme}" Foreground="White" VerticalAlignment="Center" Margin="152,0,0,0" Width="90" />
<TextBlock Text="{Binding MusteriKoduAdi}" Foreground="White" VerticalAlignment="Center" Margin="70,0,0,0" />
</DockPanel>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C# CODE
public static class FrameworkElementExtensions
{
public static FrameworkElement FindDescendantByName(this FrameworkElement element, string name)
{
if (element == null || string.IsNullOrWhiteSpace(name)) { return null; }
if (name.Equals(element.Name, StringComparison.OrdinalIgnoreCase))
{
return element;
}
var childCount = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < childCount; i++)
{
var result = (VisualTreeHelper.GetChild(element, i) as FrameworkElement).FindDescendantByName(name);
if (result != null) { return result; }
}
return null;
}
}
private void closeAll_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// StackPanel panel = LayoutHelper.FindElement(listBoxEditPast, n => n.GetType() == typeof(StackPanel)) as StackPanel;
for (int i = 0; i < listBoxEditPast.Items.Count; i++)
{
var element = listBoxEditPast.ItemContainerGenerator.ContainerFromIndex(i) as FrameworkElement;
if (element != null)
{
var sp = element.FindDescendantByName("stackPanelDetay") as StackPanel;
if (sp != null)
{
sp.Visibility = Visibility.Collapsed;
}
}
}
}
noting to do with the visualtreehelper, this is because the list is virtualized, so only the first ten items are created and then replaced by the ten next....and you loose your modifications
you must not work with the element in the data template by code
iterate through your data to set a boolean to true/false for all and then change the stack and bind the visibility to this boolean
<StackPanel Grid.Row="1" Name="stackPanelDetay" Visibility="{Binding myBoolean, Converter=BoolToVisibility}">
Requirement:-
Want to show the contact list with alphabets groups.
Using Long list selector displays the contacts list. In xaml, we mention the IsFlatList="false" in long list selector for grouping, but it displays the contacts list without groups like list box.
I herewith attached my code for your comments, please let me know where I did mistake in my code.
<phone:PhoneApplicationPage.Resources>
<!--Heading for the items(a,b,c,d) -->
<DataTemplate x:Key="GroupItemHeaderTemplate">
<Border Background="Transparent" Padding="5">
<Border Background="{StaticResource PhoneAccentBrush}" BorderBrush="{StaticResource PhoneAccentBrush}" BorderThickness="2" Width="480" Height="40" Margin="0,0,18,0" HorizontalAlignment="Left">
<TextBlock Text="{Binding Key}" Foreground="{StaticResource PhoneForegroundBrush}" FontSize="20" Padding="6" FontFamily="{StaticResource PhoneFontFamilySemiLight}" HorizontalAlignment="left" VerticalAlignment="Center"/>
</Border>
</Border>
</DataTemplate>
<!-- Heading For the list -->
<DataTemplate x:Key="ListHeader">
<Border Background="#FF049ED6" Height="40">
<TextBlock Text= "{Binding Key}" />
</Border>
</DataTemplate>
<!--Items to display-->
<DataTemplate x:Key="ItemTemplate" >
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ListImage}" Height="100" Width="100" Stretch="Uniform" Margin="10,2,0,0" ImageFailed="Image_ImageFailed" />
<TextBlock Text="{Binding ListFullName}" Width="200" Foreground="Black" Margin="10,10,0,0" FontWeight="SemiBold" FontSize="22" />
<TextBlock Text="{Binding ListBio}" FlowDirection="LeftToRight" Foreground="Black" Margin="-200,50,0,0" FontWeight="ExtraLight" FontSize="20" />
</StackPanel>
</DataTemplate>
<!--Group Intems Panel to show when click on Items Header-->
<ItemsPanelTemplate x:Key="GroupItemsPanel">
<toolkit:WrapPanel ItemHeight="105" ItemWidth="105"></toolkit:WrapPanel>
</ItemsPanelTemplate>
</phone:PhoneApplicationPage.Resources>
<toolkit:LongListSelector x:Name="LongListSelectorListBox" ItemsSource="{Binding Content}"
Margin="0,235,5,104" Width="480" Background="Transparent" IsFlatList="True"
DisplayAllGroups="False" ItemTemplate="{StaticResource ItemTemplate}"
GroupHeaderTemplate="{StaticResource GroupItemHeaderTemplate}"
ListHeaderTemplate="{StaticResource ListHeader}" GroupItemsPanel="{StaticResource GroupItemsPanel}"
SelectionChanged="LongListSelectorListBox_SelectionChanged" />
ViewModel:-
ServiceModel sm = new ServiceModel();
Content = new ObservableCollection<ListContactsModel>();
Content1 = new ObservableCollection<ListContactsModel>();
ServiceConstants.Temp_Response = x;//Save The response temp
ObservableCollection<ListContactsModel> result = ListContactsModel.extract(x, sm, OutGoingInvitation);
ObservableCollection<ListContactsModel> result1 = ListContactsModel.extract(x, sm, IncomeInvitation);
AppGlobalConstants.Temp_Response = result;
if (!((string.IsNullOrEmpty(sm.NetErrorCode)) && (string.IsNullOrEmpty(sm.ProvResErrCode))))
{
string errCode = !string.IsNullOrEmpty(sm.NetErrorCode) ? sm.NetErrorCode : sm.ProvResErrCode;
string errDesc = !string.IsNullOrEmpty(sm.NetErrorDesc) ? sm.NetErrorDesc : sm.ProvResErrDesc;
MessageBox.Show(errCode + "/" + errDesc);
}else if (result.Count > 0)
{
Content.Clear();
Content1.Clear();
Content = result;//Outgoing Invitations
Content1 = result1;//Incoming Invitations
List<AlphaKeyGroup<ListContactsModel>> DataSource = AlphaKeyGroup<ListContactsModel>.CreateGroups(result,
System.Threading.Thread.CurrentThread.CurrentUICulture,
(ListContactsModel s) => { return s.ListFullName; },
true);
Console.WriteLine("Content.Count==>>" + Content.Count);
Console.WriteLine("DataSource.ElementAt(1).Key==>>" + DataSource.ElementAt(1).Key);
Console.WriteLine("DataSource.ElementAt(2).Key==>>" + DataSource.ElementAt(2).Key);
Regards,
Naresh T
I don't see whole code and I don't know what is ListContactsModel. Is it a collection (inherits from IEnumerable/List/...)? Does it have Items propery? Does it have GetEnumerator methods?
As far as I understand AlphaKeyGroup class was taken from here (if not, read it first) http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj244365(v=vs.105).aspx
So maybe you want to bind LongListSelector to some property, that receive data from DataSource and has the same type List<_AlphaKeyGroup<ListContactsModel>_> (not to Content)?
Here is a couple of articles about LongListSelector:
http://www.geekchamp.com/articles/wp7-longlistselector-in-depth--part1-visual-structure-and-api
http://www.geekchamp.com/articles/wp7-longlistselector-in-depth--part2-data-binding-scenarios (this one will be great for you)
First of all, follow the instructions.
In general grouping in LLS means, that you have collection of items, that consist of Key/Title/Header/whatever and inner collection of group elements.
In my Wpf application, I've two datatemplates. DefaultDataTemplate and EditableDataTemplate.
Xaml:
<DataTemplate x:Key="DefaultDataTemplate" >
<StackPanel Orientation="Horizontal" Width="596">
<TextBlock Text="{Binding ClientNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="145"/>
<TextBlock Text="{Binding ApplicationNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="90"/>
<TextBlock Text="{Binding StartTimeBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="100"/>
<TextBlock Text="{Binding StopTimeBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="60"/>
<TextBlock Text="{Binding TaskNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="71"/>
<TextBlock Text="{Binding ProjectNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="130"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="EditableDataTemplate">
<StackPanel Orientation="Horizontal" Width="596">
<!--<ComboBox x:Name="ClientComboBox" SelectionChanged="ClientComboBoxChanged" ItemsSource="{Binding Path=clientList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name" SelectedItem="{Binding ClientNameBindingClass, Mode=OneWayToSource}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="145"/>-->
<TextBox Text="{Binding ClientNameBinding,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="145"/>
<TextBox Text="{Binding ApplicationNameBinding}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="90"/>
<xctk:TimePicker Name="StartPicker" Value="{Binding StartValue, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="100" EndTime="11:59:0"/>
<xctk:TimePicker Name="EndPicker" Value="{Binding EndValue, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="60" EndTime="11:59:0"/>
<TextBox Text="{Binding TaskNameBinding}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="71"/>
<ComboBox x:Name="ProjectComboBox" ItemsSource="{Binding Path=projectList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name" SelectedItem="{Binding ProjectNameBindingClass, Mode=OneWayToSource}" Width="130" Background="Yellow" BorderThickness="0"/>
</StackPanel>
</DataTemplate>
In the following code, I'm trying to change datatemplate so that I can edit existing data entries of the listbox. As per below code, when I move from DefaultDataTemplate to EditableDataTemplate, I can edit all the entries because all entries in edit mode. After editing is done when I click on button again,I just want to post that entry which I changed (whose text changed/ updated). But the problem is, on button click all the entries are getting posted to the web account to which I linked.
C#:
private void EditButton_Click(object sender, RoutedEventArgs e)
{
foreach (Harvest_TimeSheetEntry item in listBox1.Items)
{
if (item.isSynced)
{
item.isSynced = false;
listBox1.ItemTemplate = (DataTemplate)this.FindResource("EditableDataTemplate");
this.EditButton.Content = "Done Editing";
}
else
{
listBox1.ItemTemplate = (DataTemplate)this.FindResource("DefaultDataTemplate");
this.EditButton.Content = "Edit";
Globals._globalController.harvestManager.postHarvestEntry(item);
System.Windows.MessageBox.Show("Entry posted");
}
}
}
Below line is used for posting entry to Web account-
Globals._globalController.harvestManager.postHarvestEntry(item);
Please suggest something, how should I proceed?
You can add in the class Harvest_TimeSheetEntry a Property "DirtyFlag" that indicates that at least one value was changed.
public class Harvest_TimeSheetEntry
{
public bool DirtyFlag {get; private set;}
public void Reset()
{
DirtyFlag = false;
}
public DateTime StartValue
{
get { return _startValue; }
set
{
_startValue = value;
// in each of the modifyable Properties add this
DirtyFlag = true;
}
}
(...)
}
In your Button Event Handler you check then for this Flag:
private void EditButton_Click(object sender, RoutedEventArgs e)
{
foreach (Harvest_TimeSheetEntry item in listBox1.Items)
{
if (item.isSynced)
{
item.Reset();
item.isSynced = false;
listBox1.ItemTemplate = (DataTemplate)this.FindResource("EditableDataTemplate");
this.EditButton.Content = "Done Editing";
}
else
{
listBox1.ItemTemplate = (DataTemplate)this.FindResource("DefaultDataTemplate");
this.EditButton.Content = "Edit";
if(item.DirtyFlag)
{
Globals._globalController.harvestManager.postHarvestEntry(item);
item.Reset();
System.Windows.MessageBox.Show("Entry posted");
}
}
}
}
I have a windows phone project about news from media.
On this project, I have a panaroma item. In my first screeen, I get the news from my web API.
I use longlist selector to get these news but I want to put first/hot/newest new on the top with big picture of it and the text. But I couldn't gave the source rightly on my grid and LongListSelector at the same time.
In short, I want to list my news "one under the other" and the newest/first new will be big pictured on the top.
Here is what I've tried;
MAINPAGE.XAML
<!--Panorama item one-->
<phone:PanoramaItem Header="Haberler" Foreground="DarkGreen">
<ScrollViewer VerticalScrollBarVisibility="Auto" Background="White">
<StackPanel Orientation="Vertical">
<Grid x:Name="HeadNew">
<TextBlock x:Name="textBlock14" Text="{Binding Path=TITLE}" TextWrapping="Wrap" Margin="20,0" FontSize="{StaticResource PhoneFontSizeLarge}" Foreground="Black"/>
<Border Width="400" Height="250">
<Border.Background>
<ImageBrush Stretch="Uniform" ImageSource="{Binding Path=MF658370_IMAGE}"/>
</Border.Background>
</Border>
</Grid>
<phone:LongListSelector x:Name="MainLongListSelector" Background="White" Margin="-20,0,0,0" Height="Auto" Loaded="MainLongListSelectorLoaded" SelectionChanged="MainLongListSelectorSelectionChanged" toolkit:TiltEffect.IsTiltEnabled="True">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="12,2,0,4" Height="Auto" Width="Auto">
<Border Width="126" Height="70">
<Border.Background>
<ImageBrush Stretch="Uniform" ImageSource="{Binding Path=MF12670_IMAGE}"/>
</Border.Background>
</Border>
<TextBlock x:Name="textBlock1" Text="{Binding Path=TITLE}" Margin="10,0" FontSize="{StaticResource PhoneFontSizeMedium}" Foreground="Black" />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</StackPanel>
</ScrollViewer>
</phone:PanoramaItem>
Here is the MAINPAGE.XAML.CS
private void MainLongListSelectorLoaded(object sender, RoutedEventArgs e)
{
const string url = "MY_WEB_API_URL";
var hWebRequest = (HttpWebRequest)WebRequest.Create(url);
hWebRequest.Method = "GET";
hWebRequest.BeginGetResponse(MainLongListSelectorLoadCompleted, hWebRequest);
}
private void MainLongListSelectorLoadCompleted(IAsyncResult arr)
{
var request = (HttpWebRequest)arr.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(arr);
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
_json = streamReader.ReadToEnd();
Headlines = JsonConvert.DeserializeObject<FanatikApiAll.RootObject>(_json);
}
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MainLongListSelector.ItemsSource = Headlines.Headline;
});
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
HeadNew.DataContext = Headlines.Headline;
});
}
Since HeadNew isn't a list control, you need to assign only the item you need, not the whole list. For instance, to get the first item if any:
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
HeadNew.DataContext = Headlines.Headline.FirstOrDefault();
});
I have a ListBox, an IEnumerable is the data source. When a ListBoxItem is clicked, I want access to that object so I can grab some data and show another window.
Here is my ListBox XAML
`<ListBox Name="listBox1" Margin="0" Width="1010" Height="275" BorderThickness="0" BorderBrush="{x:Null}" Cursor="Arrow" HorizontalAlignment="Center" VerticalAlignment="Top" SelectionMode="Single" FontFamily="DIN" ScrollViewer.HorizontalScrollBarVisibility="Hidden" Focusable="False" IsHitTestVisible="False" IsTextSearchEnabled="False" >`
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBox_MouseLeftButtonDown"></EventSetter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:Offer}">
<StackPanel Margin="0" Width="200" Height="275" Background="Black" Name="sp">
<Image Source="{Binding Image}" Width="200" Height="131" Margin="0"></Image>
<TextBlock Padding="5" Background="Black" Text="{Binding Name}" Foreground="White" FontFamily="DIN medium" FontWeight="Bold" FontSize="16" Width="200" Margin="0"></TextBlock>
<TextBlock Padding="5,0,5,0" Background="Black" Text="{Binding Date}" Foreground="White" FontFamily="DIN medium" FontWeight="Bold" FontSize="14" Width="200" Margin="0"></TextBlock>
<TextBlock Padding="5" Background="Black" Text="{Binding Description}" Foreground="White" FontFamily="DIN light" FontSize="16" Width="200" Margin="0" TextWrapping="WrapWithOverflow"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Background="Black" CanHorizontallyScroll="True" CanVerticallyScroll="False" FlowDirection="LeftToRight" Margin="0" Orientation="Horizontal" Width="1010" Height="275"></VirtualizingStackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>`$
other pertinent info
CurrentItems = (from offerCatType in offerRes.OfferCategory
where offerCatType.type == Type
from offers in offerCatType.Offer
where new DateTime(Convert.ToDateTime(offers.startDate).Year,
Convert.ToDateTime(offers.startDate).Month, 1) <= MonthYear && Convert.ToDateTime(offers.endDate) >= MonthYear
select new Offer
{
Name = offers.name,
Description = offers.description,
Date = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(offers.startDate)) + " to " + String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(offers.endDate)),
ClickThruUrl = offers.ChannelInfo.refClickThroughLink,
ReferenceID = offers.ChannelInfo.refId,
Image = offers.ChannelInfo.refLink
}
);
listBox1.ItemsSource = CurrentItems;
protected void ListBox_MouseLeftButtonDown(object sender, RoutedEventArgs e)
{}
Is it possible some of my styling could blow away this event? I had it working earlier today, then was fixing a couple more styling items, then, the click code stopped working.
Set the IsHitTestVisible property to true instead of false for the listbox and you will get mouse events.