My page having city listing and searching functionality. When page first time loading, it is showing all record.
When user enter search Text and tap on search button. it is not updating gridview list. I check by placing debug point my code is working fine. but gridview list not showing updated list.
Following is my code.
XAML:
<StackPanel VerticalAlignment="Top">
<TextBlock Style="{StaticResource ListTextBlockStyle}" FontWeight="Bold" Text="{Binding Description}" />
<TextBlock Style="{StaticResource ListTextBlockStyle}" Text="{Binding Description}" />
</StackPanel>
<TextBlock Style="{StaticResource DistanceTextBlockStyle}" TextWrapping="Wrap" Text="XXXm" />
<Image Width="10" VerticalAlignment="Center" Source="ms-appx:///Assets/arrowright.png"/>
</StackPanel>
<Rectangle Height="1" Stroke="Black" StrokeThickness="0.5" Margin="0,3,0,0" />
</StackPanel>
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<Border Grid.Row="1" Height="60" VerticalAlignment="Bottom">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<TextBox x:Name="txtSearch" Margin="0,0,10,0" TextWrapping="Wrap" PlaceholderText="Search" VerticalAlignment="Center" Width="300" Height="50" />
<Image x:Name="imgSearch" Height="50" Width="50" Source="ms-appx:///Assets/btnSearch.png" Tapped="imgSearch_Tapped"/>
</StackPanel>
</StackPanel>
</Border>
C#:
public List<City> gs_CityList = new List<City>();
protected override void OnNavigatedTo(NavigationEventArgs e)
{
fillCityList();
}
private void fillCityList()
{
gs_CityList.Clear();
if (string.IsNullOrEmpty(CityListManagerManager.ms_searchTxt))
{
foreach (City foCity in CityListManagerManager.ms_CityList)
{
City loCity = new City();
loCity.Description = foCity.Description.Replace("\n", "").Substring(0, 15) + "...";
loCity.longtitude = foCity.longtitude;
loCity.latitude = foCity.latitude;
loCity.Location = foCity.Location;
gs_CityList.Add(loCity);
}
}
else
{
foreach (City foCity in CityListManagerManager.ms_CityList.Where(p => p.Description.ToLower().Contains(CityListManagerManager.ms_searchTxt.ToLower())))
{
City loCity = new City();
loCity.Description = foCity.Description.Replace("\n", "").Substring(0, 15) + "...";
loCity.longtitude = foCity.longtitude;
loCity.latitude = foCity.latitude;
loCity.Location = foCity.Location;
gs_CityList.Add(loAEDPin);
}
txtSearch.Text = CityListManagerManager.ms_searchTxt;
}
if (gs_CityList.Count > 0)
{
gvCityList.DataContext = gs_CityList; // --- This binding data to gridview
}
else
MessageBox("City not found...!");
}
private void imgSearch_Tapped(object sender, TappedRoutedEventArgs e)
{
CityListManagerManager.ms_searchTxt = txtSearch.Text.Trim();
fillCityList();
}
You should try changing your List<City> into an ObservableCollection<City>, as this allows the binding to get notified about changes.
You could also think about using a CollectionViewSource as data source for the GridView and modifying its Filter property instead of re-filling the collection.
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}">
I want to update DownloadingSpeed Property which is binded to TextBox in a ListBoxItem. I am generating ListBoxItems in c#. Please guide me how do i update Binding Content of TextBoxes within a ListItemBox in C#.
WPF LisBox Code
<ListBox Width="Auto"
Name="WebsiteList"
MouseUp="SelectedListItem"
SelectedIndex="0"
Grid.Column="1"
Grid.Row="2"
Grid.RowSpan="2"
Margin="0,0,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="920">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Grid Width="920">
<TextBlock FontWeight="Bold" FontSize="18" Width="Auto">
<Hyperlink NavigateUri="http://google.com" FontStyle="Italic">
<Label Content="{Binding WebsiteTitle}" /><Label FontSize="10" Margin="0,0,0,3" Content="{Binding DirectorySize}" />
</Hyperlink>
</TextBlock>
<TextBlock Width="0" TextAlignment="right">
<TextBlock Visibility="Hidden" Text="{Binding DownloadID}"/>
<TextBlock Visibility="Hidden" Text="{Binding DirectoryPath}"/>
<TextBlock Visibility="Hidden" Text="{Binding CurrentTime}"/>
<TextBlock Visibility="Hidden" Text="{Binding CurrentDate}"/>
<TextBlock Visibility="Hidden" Text="{Binding GivenUrl}"/>
</TextBlock>
</Grid>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Grid Width="920">
<ProgressBar Name="progress1" Maximum="100" Minimum="0" Value="30" Background="#FFF" Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}, Path=Width}" Height="10" />
</Grid>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Grid Width="920">
<TextBlock HorizontalAlignment="Left" Width="Auto">Status: <TextBlock Text="{Binding Status}"/></TextBlock>
<TextBlock Width="Auto" TextAlignment="right">
<TextBlock Text="Downloading Speed: "/>
<TextBlock Name="DownloadingSpeed" Text="{Binding DownloadingSpeed}"/>
</TextBlock>
</Grid>
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
In MainWindow.xaml.cs
private void GenerateList()
{
List<Download> WebsitesList = new List<Download>();
WebsitesList.Add(new Download() {DownloadID = ID, WebsiteTitle = WebTitle, Status = WebStatus, CurrentTime = CurrentTime,CurrentDate = CurrentDate, DownloadingSpeed = DownloadSpeed, DirectoryPath = path, DirectorySize = helper.GetDirectorySize(path),GivenUrl = url });
WebsiteList.ItemsSource = WebsitesList;
}
//get download speed and update DownloadingSpeed
private void updateDownloadingSpeed(object sender, EventArgs e)
{
interfaceStats = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics();
downloadspeed = (interfaceStats.BytesReceived - previousbytesreceived) / 1024;
previousbytesreceived = NetworkInterface.GetAllNetworkInterfaces()[0].GetIPv4Statistics().BytesReceived;
Download.DownloadingSpeed = Math.Round(downloadspeed, 2) + " KB/s"; //Rounding to 2 decimal places and save in DownloadSpeed Property
}
In Download.cs
public class Download : INotifyPropertyChanged
{
private string _DownloadingSpeed = "0 kb/s";
public string DownloadingSpeed
{
get { return _DownloadingSpeed; }
set
{
if (_DownloadingSpeed == value)
return;
_DownloadingSpeed = value;
this.OnPropertyChanged("DownloadingSpeed");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Add UpdateSourceTrigger for TextBlock.
<TextBlock Name="DownloadingSpeed" Text="{Binding DownloadingSpeed, UpdateSourceTrigger=PropertyChanged}"/>
You might find that your code works if you use WPF properly by defining properties and declaring XAML correctly. It is customary to have an ObservableCollection<T> property that you data bind to the UI collection control. You would then data bind it to the ItemsSource property of the control:
<ListBox ItemsSource="{Binding Items}" ... />
Then, when you want to update any properties of the items, you need to set the properties of the items. This:
Download.DownloadingSpeed = Math.Round(downloadspeed, 2) + " KB/s";
... is not setting the property of an item from the collection. To do that, you'd need to do something like this:
// Use whatever filter you want to find the correct item from the collection
Download downloadInstance = Items.Where(d => d.Name == "SomeName").First();
downloadInstance.DownloadingSpeed = Math.Round(downloadspeed, 2) + " KB/s";
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!
I want to access the text content after binding of the "GameName" textblock that is inside the listbox.
<controls:PanoramaItem Header="games" Margin="0" Height="800" Foreground="White" VerticalAlignment="Center">
<!--Double line list with text wrapping-->
<ListBox x:Name="GamesListBox" Margin="0,0,-12,66" Height="614" ItemsSource="{Binding dataFeed}" SelectionChanged="GamesListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<!--Replace rectangle with image-->
<Image Height="100" Width="100" Source="{Binding AllGamesImage}" Margin="12,0,9,0" VerticalAlignment="Top" HorizontalAlignment="Left" Stretch="UniformToFill" />
<StackPanel Width="311">
<TextBlock x:Name="GameName" Text="{Binding AllGamesTitle}" TextWrapping="Wrap" Foreground="White" Style="{StaticResource PhoneTextExtraLargeStyle}" Margin="0,0,0,1"/>
<TextBlock Text="{Binding AllGamesDescription}" TextWrapping="Wrap" Margin="0,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PanoramaItem>
i want to take whatever is set as the text content and pass it to another page as a parameter or anything.
code behind after Shawn Kendrot suggestion.
private void GamesListBox_SelectionChanged(object sender, EventArgs e)
{
var myObject = GamesListBox.SelectedItem as NewGamesClass;
string gameName = myObject.TitleCode;
NavigationService.Navigate(new Uri("/Pages/AchivementListPage.xaml?gameName=" + gameName, UriKind.Relative));
}
i get a NullExeception when returing to the page here:
string gameName = myObject.TitleCode;
Why access the Text property when you can access the property of the object?
void GamesListBox_SelectionChanged(object sender, EventArgs e)
{
var myObject = GamesListBox.SelectedItem as MyObject;
string gameName = myObject.AllGamesTitle;
// Do something with gameName
}
Try this
ListBoxItem selItem = (ListBoxItem)(listboxWeight.ItemContainerGenerator.ContainerFromIndex(listboxWeight.SelectedIndex));
StackPanel weightpanel = (StackPanel)selItem.Content;
var child1 = weightpanel.Children[0] as TextBlock;
var child2 = weightpanel.Children[1] as TextBlock;
I have a list box like below.
<ListBox x:Name="CouponListBox" ItemsSource="{Binding Item}" SelectionChanged="CouponListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding MerchantImage}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="130">
<TextBlock Text="{Binding CustomerName}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding MerchantName}" TextWrapping="Wrap" FontSize="20" Foreground="#FFC4C4C4" Padding="10" />
<TextBlock Text="{Binding Distance}" TextWrapping="Wrap" FontSize="16" Foreground="#FFC4C4C4" Padding="10" />
<TextBlock Text="{Binding DistanceInMinutes}" TextWrapping="Wrap" FontSize="16" Foreground="#FFC4C4C4" Padding="10" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And I have a Change Event in .cs file which is
private void CouponListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// If selected index is -1 (no selection) do nothing
if (CouponListBox.SelectedIndex == -1)
return;
// Navigate to the new page
System.Diagnostics.Debug.WriteLine("this is a test::" + CouponListBox.SelectedItem.ToString());
NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + CouponListBox.SelectedIndex, UriKind.Relative));
// Reset selected index to -1 (no selection)
CouponListBox.SelectedIndex = -1;
}
In DetailsPage I could able to print the item Index. But What I want is Customer ID passed in the URL like
"/DetailsPage.xaml?selectedItem=" + CouponListBox.SelectedIndex + "&customerId=" + couponId
Can anyone please tell me where I should include customerId in my XAML file? and that who can I call it in the function.
Thank you,
Karthik
Use this:
if (this.NavigationContext.QueryString.ContainsKey("customerId"))
{
string customerId = this.NavigationContext.QueryString["customerId"];
}
if (this.NavigationContext.QueryString.ContainsKey("selectedItem"))
{
string selectedItem = this.NavigationContext.QueryString["selectedItem"];
}
in the usercontrol's Loaded or other appropriate event.