My ListBox control is working fine, except that the data to be bound is not displaying.
My XAML:
<ListBox x:Name="listFileNames" SelectionMode="Single" Margin="10">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Image Margin="5" Source="{Binding Path=Image}" Stretch="Fill" Width="50" Height="50"></Image>
<StackPanel Grid.Column="1" Margin="5">
<TextBlock Text="{Binding Path=FileName}" FontWeight="Bold"></TextBlock>
<TextBlock Text="{Binding Path=State}"></TextBlock>
<TextBlock Text="This text shows..."></TextBlock>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
My code:
public struct StyleDocumentFile
{
public string Image;
public string FileName;
public string State;
}
// ......
StyleDocumentFile sdf = new StyleDocumentFile()
{
Image = "/Images/Loading.png",
FileName = "abc",
State = "Extracting Data...",
};
this.listFileNames.Items.Add(sdf);
Change fields to Property. After this, all works fine.
public struct StyleDocumentFile
{
public string Image { get; set; }
public string FileName { get; set; }
public string State { get; set; }
}
You should set ItemsSource in ListBox definition like ItemsSource="{Binding Model.Items}". In addition you must call RaisePropertyChanged in setter of model properties.
Related
The data is coming through fine, and I can successfully display the data the in a list box, but when i try to do this in a grid view or list view, i get these results. I feel like something small is missing here.
I've set the two way, and update property source on the textboxes, but still no visible data shown. I know it has the data, because it expands like I captured in this screenshot.
LeadingCauseOfDeath Class
public class LeadingCausesOfDeath : BasePropertyHandler
{
public int Year { get; set; }
public string _113_cause_name { get;set;}
public string Cause_name { get; set; }
public string State { get; set; }
public int Deaths { get; set; }
public int AgeAdjustedDeathRate { get; set; }
}
XAML View
<Grid DataContext="{Binding Source={StaticResource HomePageVM}}">
<StackPanel >
<NavigationView PaneDisplayMode="Top" IsBackButtonVisible="Collapsed" >
<NavigationView.MenuItems>
<NavigationViewItem Content="Family"/>
<NavigationViewItem Content="History"/>
<NavigationViewItem Content="About"/>
</NavigationView.MenuItems>
</NavigationView>
<GridView ItemsSource="{Binding Data, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
IsItemClickEnabled="True"
IsSwipeEnabled="true"
SelectionMode="Single"
BorderThickness="10" BorderBrush="Blue">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid MaximumRowsOrColumns="4" Orientation="Vertical"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<DataTemplate>
<Grid BorderBrush="Black" BorderThickness="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Cause_name}" />
<TextBlock Grid.Column="1" Text="{Binding Year}" />
<TextBlock Grid.Column="2" Text="{Binding Deaths}" />
<TextBlock Grid.Column="3" Text="{Binding State}" />
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</StackPanel>
</Grid>
View model
private ObservableCollection<LeadingCausesOfDeath> _data;
public ObservableCollection<LeadingCausesOfDeath> Data
{
get
{
return _data;
}
set
{
_data = value;
OnPropertyChanged("Data");
}
}
public HomePageVM()
{
GetData();
}
private async void GetData()
{
var service = new ServiceForApi();
Data = new ObservableCollection<LeadingCausesOfDeath>();
Data = await service.GetFDAStuff();
OnPropertyChanged("Data");
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged( string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Putting a GridView inside a StackPanel is a bad idea. StackPanel will expand as much as it needs to fit the entire content. So, the automatic virtualization that GridView does is lost because it stretches to fit all the items.
With your ItemsWrapGrid's Orientation set to Vertical, it's probably not expanding at all... it expects a fixed height to fill with items and will expand in the horizontal direction.
Use a Grid with two RowDefinitions... first set to Auto, second set to *
i have a multicolumn ListBox as you can see below.
<ListBox x:Name="lstQuestions" HorizontalAlignment="Left" Height="544" VerticalAlignment="Top" Width="175" Margin="0,0,0,-0.5" SelectionChanged="lstQuestions_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="0,2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding qID}"/>
<Image Source="{Binding imgPath}" Width="140" Height="50" Stretch="UniformToFill" Grid.Column="1"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I want to show the index number (like 1, 2, 3 ...) instead of <TextBlock Text="{Binding qID}"/> in first column, how can I do that?
Edit: Binding code behind
public class QList
{
public string qID { get; set; }
public string imgPath { get; set; }
public int ansCount { get; set; }
public string rightAns { get; set; }
}
and
public static List<QList> questions = new List<QList>();
last one
lstQuestions.ItemsSource = Test.questions;
The first two are in a class called Test
Im trying to learn how to make datatemplate in listviews in my win 8 app
I have the following code in my Xaml code
<!-- Vertical scrolling item list -->
<ListView x:Name="itemListView"
Margin="120,0,0,60"
ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
SelectionChanged="ItemListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="110" Margin="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="110" Height="110">
<Image Source="{Binding Image}" Stretch="UniformToFill"/>
</Border>
<StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Text="{Binding Title}" TextWrapping="NoWrap" FontFamily="Global User Interface"/>
<TextBlock Text="{Binding Subtitle}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Description}" MaxHeight="60" FontFamily="Global User Interface"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
What I cant work out is how to set the text for the three text blocks Title,Subtitle & Description as well as the Picture in Image
Usually When the page loads I use the following in my itemListView_Loaded(object sender, RoutedEventArgs e) method
itemListView.Items.Add(Convert.ToString(correct) + ". " + line.Split(',')[6]);
But how do I do it Im really stumped
Any help appreciated
Mark
You'll have to make a class which includes those properties.
public class MyItem
{
public string Title { get; set; }
public string Subtitle { get; set; }
public string Description { get; set; }
public string Source { get; set; }
}
Then when you add items:
var item = new MyItem();
item.Title = "Title";
item.Subtitle = "Subtitle";
item.Description = "Some example description.";
item.Source = "Assets/SomeFolder/SomeImage.png";
itemListView.Items.Add(item);
That worked in my app (AirPett Transit)
I have a ListView with a list of comments:
<ListView ItemsSource="{Binding Comments}">
<ListView.ItemTemplate>
<DataTemplate>
<Border Background="{Binding User, Converter={StaticResource UsernameToBackgroundColorConverter}}"
Margin="0,5"
HorizontalAlignment="Stretch"
FlyoutBase.AttachedFlyout="{StaticResource FlyoutBase1}"
Holding="BorderCommento_Holding">
<StackPanel>
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding User}"
FontSize="20"
Grid.Column="0"
FontWeight="Bold"
Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}"/>
<TextBlock HorizontalAlignment="Right"
Text="{Binding DateTime}"
FontSize="20"
Grid.Column="1"
Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}"/>
</Grid>
<TextBlock Margin="5,0,5,5"
Text="{Binding Text}"
FontSize="20"
TextWrapping="Wrap"/>
</StackPanel>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Comment class:
public class Comment
{
public Comment(String id, String user, String text, String date_time)
{
this.Id = id;
this.User = user;
this.Text = text;
this.DateTime = date_time;
}
public string Id { get; private set; }
public string User { get; private set; }
public string Text { get; private set; }
public string DateTime { get; private set; }
}
The Flyout menu that appears when holding on a comment is defined in Page.Resources:
<Page.Resources>
<MenuFlyout x:Name="flyout1" x:Key="FlyoutBase1">
<MenuFlyoutItem x:Name="ReportCommentFlyout"
Text="{Binding User, Converter={StaticResource ReportOrDeleteComment}}"
Click="ReportCommentFlyout_Click"/>
</MenuFlyout>
</Page.Resources>
Now, in the ReportCommentFlyout_Click I need to know the comment Id that is being reported/deleted.
How can I do it?
I've tried
string CommentId = ((Comment)e.OriginalSource).Id;
But the app crashes...
Your app crashes because you cast e.OriginalSource to Comment and it doesn't work because it's not of that type. Usually, it's often safer to way to do this by using "as"
var comment = someObject as Comment;
if (comment != null)
{
....
}
Regarding your problem, have you tried
var menuFlyoutItem = sender as MenuFlyoutItem;
if (menuFlyoutItem != null)
{
var comment = menuFlyoutItem.DataContext as Comment;
if (comment != null)
{
string CommentId = comment.Id;
}
}
So, I am on my way learning MVVM Pattern for Windows Phone, and stuck how to bind the View to my ViewModel. App that I build now is getting current and next 5 days weather and display it to one of my panorama item on MainPage.xaml using UserControl.
I cannot just simply set the Forecasts.ItemsSource = forecast; in my WeatherViewModel, it says that Forecasts (Listbox element name in WeatherView) not exist in the current context.
Can anybody teach me how to bind it? and anybody have a good source/example sample to mvvm pattern in windows-phone? Thanks before.
EDIT:
WeatherModel.cs
namespace JendelaBogor.Models
{
public class WeatherModel
{
public string Date { get; set; }
public string ObservationTime { get; set; }
public string WeatherIconURL { get; set; }
public string Temperature { get; set; }
public string TempMaxC { get; set; }
public string TempMinC { get; set; }
public string Humidity { get; set; }
public string WindSpeedKmph { get; set; }
}
}
WeatherViewModel.cs
namespace JendelaBogor.ViewModels
{
public class WeatherViewModel : ViewModelBase
{
private string weatherURL = "http://free.worldweatheronline.com/feed/weather.ashx?q=";
private const string City = "Bogor,Indonesia";
private const string APIKey = "APIKEY";
private IList<WeatherModel> _forecasts;
public IList<WeatherModel> Forecasts
{
get
{
if (_forecasts == null)
{
_forecasts = new List<WeatherModel>();
}
return _forecasts;
}
private set
{
_forecasts = value;
if (value != _forecasts)
{
_forecasts = value;
this.NotifyPropertyChanged("Forecasts");
}
}
}
public WeatherViewModel()
{
WebClient downloader = new WebClient();
Uri uri = new Uri(weatherURL + City + "&num_of_days=5&extra=localObsTime&format=xml&key=" + APIKey, UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ForecastDownloaded);
downloader.DownloadStringAsync(uri);
}
private void ForecastDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("Cannot load Weather Forecast!");
}
else
{
XDocument document = XDocument.Parse(e.Result);
var current = from query in document.Descendants("current_condition")
select new WeatherModel
{
ObservationTime = DateTime.Parse((string)query.Element("localObsDateTime")).ToString("HH:mm tt"),
Temperature = (string)query.Element("temp_C"),
WeatherIconURL = (string)query.Element("weatherIconUrl"),
Humidity = (string)query.Element("humidity"),
WindSpeedKmph = (string)query.Element("windspeedKmph")
};
this.Forecasts = (from query in document.Descendants("weather")
select new WeatherModel
{
Date = DateTime.Parse((string)query.Element("date")).ToString("dddd"),
TempMaxC = (string)query.Element("tempMaxC"),
TempMinC = (string)query.Element("tempMinC"),
WeatherIconURL = (string)query.Element("weatherIconUrl")
}).ToList();
}
}
}
}
WeatherView.xaml
<UserControl x:Class="JendelaBogor.Views.WeatherView"
xmlns:vm="clr-namespace:JendelaBogor.ViewModels">
<UserControl.DataContext>
<vm:WeatherViewModel />
</UserControl.DataContext>
<Grid Margin="0,-10,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid x:Name="Current" Grid.Row="0" Height="150" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" delay:LowProfileImageLoader.UriSource="{Binding WeatherIconURL}" Width="120" Height="120" VerticalAlignment="Top"/>
<StackPanel Grid.Column="1" Height="200" VerticalAlignment="Top">
<TextBlock Text="{Binding Temperature}" FontSize="22"/>
<TextBlock Text="{Binding ObservationTime}" FontSize="22"/>
<TextBlock Text="{Binding Humidity}" FontSize="22"/>
<TextBlock Text="{Binding Windspeed}" FontSize="22"/>
</StackPanel>
</Grid>
<Grid Grid.Row="1" Height="300" VerticalAlignment="Bottom" Margin="10,0,0,0">
<StackPanel VerticalAlignment="Top">
<StackPanel Height="40" Orientation="Horizontal" Margin="0,0,0,0">
<TextBlock Text="Date" FontSize="22" Width="170"/>
<TextBlock Text="FC" FontSize="22" Width="60"/>
<TextBlock Text="Max" TextAlignment="Right" FontSize="22" Width="90"/>
<TextBlock Text="Min" TextAlignment="Right" FontSize="22" Width="90"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ListBox ItemsSource="{Binding Forecasts}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Height="40" Orientation="Horizontal" Margin="0,10,0,0">
<TextBlock Text="{Binding Date}" FontSize="22" TextAlignment="Left" Width="170" />
<Image delay:LowProfileImageLoader.UriSource="{Binding WeatherIconURL}" Width="40" Height="40" />
<TextBlock Text="{Binding TempMaxC, StringFormat='\{0\} °C'}" TextAlignment="Right" FontSize="22" Width="90" />
<TextBlock Text="{Binding TempMinC, StringFormat='\{0\} °C'}" TextAlignment="Right" FontSize="22" Width="90" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</StackPanel>
</Grid>
</Grid>
</UserControl>
MainPage.xaml
<controls:PanoramaItem x:Name="Weather" Header="weather">
<views:WeatherView />
</controls:PanoramaItem>
You need to tell the view what viewmodel you are using. By adding
<UserControl
xmlns:vm="clr-namespace:JendelaBogor.ViewModels">
<UserControl.DataContext>
<vm:WeatherViewModel />
</UserControl.DataContext>
</UserControl>
all {Binding}'s are mapped to the class WeatherViewModel. By using the ItemsSource property on the listbox as Reed suggests you can then bind all items from a list that you expose through a property.
If the list is ever changed while running the application, consider using an ObservableCollection and clearing it and adding all new items when new data is received. If you do, your GUI will simply update with it.
The ViewModel doesn't know about the view.
You need to make a Forecasts property on the ViewModel, and bind the ItemsSource to it from your View. In your view, change the ListBox to:
<!-- No need for a name - just add the binding -->
<ListBox ItemsSource="{Binding Forecasts}">
Then, in your ViewModel, add:
// Add a backing field
private IList<WeatherModel> forecasts;
// Add a property implementing INPC
public IList<WeatherModel> Forecasts
{
get { return forecasts; }
private set
{
forecasts = value;
this.RaisePropertyChanged("Forecasts");
}
}
You can then set this in your method:
this.Forecasts = (from query in document.Descendants("weather")
select new WeatherModel
{
Date = DateTime.Parse((string)query.Element("date")).ToString("dddd"),
TempMaxC = (string)query.Element("tempMaxC"),
TempMinC = (string)query.Element("tempMinC"),
WeatherIconURL = (string)query.Element("weatherIconUrl")
})
.ToList(); // Turn this into a List<T>