Class File:
public class User
{
public string user { get; set; }
}
XML for the TextBlock:
<DataTemplate x:Key="DataTemplate1">
<StackPanel x:Name="Stak" Orientation="Vertical" Width="0">
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding}" Width="443" Margin="0,0,-443,0" FontSize="22"/>
<TextBlock x:Name="UserText" HorizontalAlignment="Left" Text="{Binding User}" TextWrapping="NoWrap" Width="443" Margin="0,0,-443,0" FontFamily="Segoe WP SemiLight" FontSize="23"/>
</StackPanel>
</DataTemplate>
C# code to load text:
IsolatedStorageFileStream readName = store.OpenFile("/User Information/UserName.txt", FileMode.Open, FileAccess.Read);
using (StreamReader contactName = new StreamReader(readName))
{
var name = contactName.ReadLine();
var Load = new User();
Load.user = name;
}
So Basically what this is supposed to do is when the app loads, it reads a file from the User Information folder and is meant to add it to the TextBlock text. Because I cant access the TextBlock since it's inside a Pivot Datatemplate, I've binded it.
Once the App is done reading the file it's meant to add whatever is inside the name into the textblock but it doesn't do it.
Related
So I have a customised GridView with a data template that contains a TextBox and is populated by a list of a custom class called Player. I need to be able to retrieve both the instance of Player and the text in the TextBox and save them to a new custom class called Score.
<GridView x:Name="gridScore" ItemsSource="{x:Bind PlayerList}" IsItemClickEnabled="True">
<GridView.ItemTemplate>
<DataTemplate x:DataType="data:Player">
<StackPanel Orientation="Horizontal">
<TextBox x:Name="txtbxGridScore" TextChanged="txtbxGridScoreChangedEventHandler" />
<Image Source="{x:Bind ProfilePicture}"/>
<StackPanel VerticalAlignment="Center">
<TextBlock Text="{x:Bind FullName}" />
<TextBlock Text="{x:Bind Alias}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<Button x:Name="buttonSave" Content="Save Scores" Style="{StaticResource BarButtonStyle}" Click="buttonSave_Click"/>
I come from a web-based Java background so this is a little bit new to me but it seems like it should be a fairly simple exercise.
Initially, I tried iterating through the GridView upon a Button Click and grabbing each Player item along with the TextBox Text and saving them to a List<> of Score, however, getting the TextBox value proved troublesome.
I then tried initialising a page scope List<> of Score and simply updating it each time the TextBox value was changed, however, I wasn't able to make this work either.
A solution for either approach will work fine for my purposes. Any input is appreciated!
If I correctly understood you this is one of the way to resolve your problem.
So let's assume that your model class Player have this structure:
public class Player {
public int PlayerID { get; set; }
public string ProfilePicture { get; set; }
public string FullName { get; set; }
public string Alias { get; set; }
public float PlayerScore { get; set; } // To store textbox value
}
So you can resolve this by using two way binding.
XAML part will look something like this:
<GridView x:Name="gridScore"
ItemsSource="{x:Bind PlayerList}"
IsItemClickEnabled="True">
<GridView.ItemTemplate>
<DataTemplate x:DataType="data:Player">
<StackPanel Orientation="Horizontal">
<TextBox x:Name="txtbxGridScore"
Text="{x:Bind PlayerScore, Mode=TwoWay}" />
<Image Source="{x:Bind ProfilePicture}" />
<StackPanel VerticalAlignment="Center">
<TextBlock Text="{x:Bind FullName}" />
<TextBlock Text="{x:Bind Alias}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<Button x:Name="buttonSave"
Content="Save Scores"
Click="buttonSave_Click" />
I have initialized your PlayerList with some dummy data like this:
PlayerList = new ObservableCollection<Player>() {
new Player() {
FullName = "Player A", Alias = "AAA"
},
new Player () {
FullName = "Player B", Alias = "BBB"
}
};
As you can see in XAML I am binding your text box with PlayerScore property of Player model.
When I run this App I get screen like this:
I will input some data into TextBox and click Save button:
When I click on Save it will trigger the event that you wrote in Button part
In that event I have one foreach loop that will iterate through the list and one breakpoint and as you can see on first item "Player A" the PlayerScore value is 10:
Now you can find your players with some ID property or with some other way that you want. This is the most simple way to accomplish what you want.
Remark: This could be solved in a better way using MVVM pattern and other stuff but as you mentioned you are beginner so maybe it is better for you to solve it like this and after that go with more advanced technique. Hope that this was helpful for you.
I am a beginner in Windows phone programming.
I want to bind the data from API to my XAML elements using that Binding Attributes. Please let me know how can we bind multilevel classes objects in it.
Here's my scenario.
List<Sample> SearchResult = new List<Sample>()
{
new Sample(){
Name="ABC",
modelProperty = new SampleDetail(){
articleNo="1", videoURL = "https://www.youtube.com/watch?v=abc",
colors = new List<ColorsDemo>(){
new ColorsDemo {
Name = "Red",
colorProperty= new ColorDemoProperty{ name = "ABC",article_no = "Art1",
image = new Uri("http://img.youtube.com/vi/e60E99tUdxs/default.jpg",UriKind.RelativeOrAbsolute)
}
}
}
}
}
And now, I want to bind the Name of ColorsDemo class into my textblock. See what I have done to bind in XAML like this:
<TextBlock x:Name="PName" Grid.Row="0" Margin="100,0,0,0" Tap="ProductName_Tap" HorizontalAlignment="Center" VerticalAlignment="Center" Width="350" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=modelProperty.colors.Name}" FontSize="30"></TextBlock>
From your code, i see that colors is a List of ColorDemo objects. So when you say {Binding Path=modelProperty.colors.Name}it does not tell which list item to bind to. The correct usage should be {Binding Path=modelProperty.colors[0].Name}. This tells the control to bind to the name of the first color item (as index is 0).
To bind all the colors. You should use a Listview and bind the colors in it. So you should be able to do something like this.
<ListView ItemSource={Binding Path=modelProperty.colors}>
<ListView.ItemTemplate>
<TextBlock x:Name="PName" Grid.Row="0" Margin="100,0,0,0" Tap="ProductName_Tap" HorizontalAlignment="Center" VerticalAlignment="Center" Width="350" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=Name}" FontSize="30"></TextBlock>
</ListView.ItemTemplate>
</ListView>
I am making a WP8 application with a lot of local content in my Assets folder. So I am using a JSON file stored in the a JSON folder.
I have been able to parse the JSON to C# very easily and now I am trying to display the data in a list. I had no problem with displaying the title but I am unable to display an image, even with the filename I am got.
My images are stored in "Assets/Content/mediaXXX.jpg";
ListViewModel :
public class ListViewModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
public BitmapImage ListImage { get; set; }
}
XAML
<ListBox Margin="0,1,0,0"
Height="730"
x:Name="MainList">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="120"
Width="480">
<StackPanel Orientation="Horizontal">
<Image HorizontalAlignment="Left"
Source="{Binding ListImage}"
Margin="12"
Stretch="UniformToFill"
Width="130"/>
<Grid>
<TextBlock x:Name="ListItemTitle"
Text="{Binding Title}"/>
<TextBlock x:Name="ListItemSubTitle"
Text="{Binding Subtitle}"/>
</Grid>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And my C# page
BitmapImage image = new BitmapImage(new Uri(#"Assets/Content/" + photo.filename + ".jpg", UriKind.Relative);
l.ListImage = image;
Any idea?
Code should work. Only problems that might occur is your ListBox databinding is incorrectly defined.
I don't see any .ItemsSource = or ItemsSource={Binding some_collection}
Another thing is make sure that photo.filename is returning the correct file.
Set a string debug_string = "Assets/Content/" + photo.filename + ".jpg";
Make sure everything is correct.
Last thing is to make sure the files are actually in the Assets Folder inside the project and its
BuildAction is set to Content
like so
I cannot bind my sample data to textblocks in stackpanel, which I defined in resources. I think that I use style in wrong way, because I receive toString() method instead of class binded fields.
That's my resources with defined style:
<UserControl.Resources>
<ItemsPanelTemplate x:Key="VirtualizingStackPanelTemplate">
<VirtualizingStackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
<ListView x:Key="ListBoxTemplate" HorizontalAlignment="Left" ScrollViewer.HorizontalScrollBarVisibility="Visible">
<ListView.ItemTemplate>
<DataTemplate>
<!--<ListBoxItem Background="DarkOrchid" Margin="1,1, 5,5" Height="400" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch">-->
<StackPanel>
<TextBlock FontSize="30" Text="{Binding Title}"/>
<TextBlock FontSize="20" Text="{Binding Desc}"/>
</StackPanel>
<!--</ListBoxItem>-->
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</UserControl.Resources>
Here is my method in which i add listview programatically:
long rowCount = ContentGridFullView.RowDefinitions.LongCount();
if (rowCount > 8) return;
var c1 = new RowDefinition { Height = new GridLength(1, GridUnitType.Star) };
ContentGridFullView.RowDefinitions.Add(c1);
rowCount = ContentGridFullView.RowDefinitions.LongCount();
TextBlock tb = new TextBlock {Text = "TEXTBLOCK ITEM = " + (rowCount - 1), FontSize = 40};
Viewbox vb = new Viewbox { Child = tb };
if (rowCount > 8) return;
Grid.SetRow(vb, Convert.ToInt32(rowCount-1));
Grid.SetColumn(vb, 1);
ListView lb = new ListView();
lb.Style = Resources["ListBoxTemplate"] as Style;
lb.ItemsPanel = (ItemsPanelTemplate) Resources["VirtualizingStackPanelTemplate"];
var products = new ObservableCollection<Product>() { new Product("ASDASDSADAS", "VCBVCBVCBVCBC"), new Product("ASDASDSADAS", "VCBVCBVCBVCBC"), new Product("ASDASDSADAS", "VCBVCBVCBVCBC"), new Product("ASDASDSADAS", "VCBVCBVCBVCBC") };
lb.ItemsSource = products;
ContentGridFullView.Children.Add(lb);
ContentGridFullView.Children.Add(vb);
Grid.SetRow(lb, Convert.ToInt32(rowCount - 1));
Grid.SetColumn(lb, 2);
And my short class that I want to bind:
public class Product
{
public string Title { get; set; }
public string Desc { get; set; }
public Product(string title, string desc)
{
Title = title;
Desc = desc;
}
public override string ToString()
{
return "I see that message instead of Title and Desc";
}
}
Can someone tell me what's wrong with this code? Thank you.
Create your Observable collection as a property (getter/setter):
ObservableCollection<Product> _products;
public ObservableCollection<Product> products
{
get{return _products;}
set
{
_products=value;
PropertyChanged("products");
}
}
The property changed event will be need to indicate that the collection has changed,its needed when your using ObservableCollection. You'll need to read more about it.You can add items to the products collection by using :
products.Add(Product_object)
And your xaml code will have the itemsSource as follows:
<ListView x:Key="ListBoxTemplate" HorizontalAlignment="Left" ScrollViewer.HorizontalScrollBarVisibility="Visible" ItemsSource="{Binding products}">
<ListView.ItemTemplate>
<DataTemplate>
<!--<ListBoxItem Background="DarkOrchid" Margin="1,1, 5,5" Height="400" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch">-->
<StackPanel>
<TextBlock FontSize="30" Text="{Binding Title}"/>
<TextBlock FontSize="20" Text="{Binding Desc}"/>
</StackPanel>
<!--</ListBoxItem>-->
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The following statement is important in your xaml code so that your xaml code will know where to look for the data.
DataContext="{Binding RelativeSource={RelativeSource Self}, Path=x}
First try and create a static list and check if data is getting initialized properly and then you can try creating listviews dynamically. But the code above will be the same thing you will have to do create dynamic listviews.
So I created an Windows Store app (aka Windows 8 Application / previously called Metro App) and I import a zip archive that contains image (the import work well).
When the zip is exctracted (in it's own folder), I add the object that represent the folder in an ObservableCollection.
This ObservableCollection is used as DataContext to a GridView, the name of the folder is properly displayed but the first image of the folder isn't... <= so that my problem.
I create my object using an static method after the extract is completed
public class ZipFolder
{
public string Title
{
get { return _title; }
set { _title = value;}
}
public int CurrentPage
{
get { return _currentPage; }
set { _currentPage = value;}
}
public Uri PathCover
{
get { return _pathCover; }
set { _pathCover = value;}
}
private string _title ;
private int _currentPage;
private Uri _pathCover;
}
public static async Task<ZipFolderObject> CreateComic(StorageFolder folder)
{
ZipFolderObject o = new ZipFolderObject();
o.Title = folder.DisplayName;
IReadOnlyList<StorageFile> asyncOperation = await folder.GetFilesAsync();
StorageFile cover = asyncOperation[0];
o.PathCover = new Uri("ms-appdata:///local/" + folder.Name + "/" + cover.Name);
return o;
}
And the binding look like this:
<DataTemplate x:Key="zipFolderItemTemplate">
<StackPanel Width="165" Height="250">
<Grid Height="215">
<Border Background="Bisque" Width="{Binding ActualWidth, ElementName=image}">
<!--<Image x:Name="image" VerticalAlignment="Top" HorizontalAlignment="Center" Source="{Binding Cover}" />-->
<Image Stretch="Uniform" x:Name="image" VerticalAlignment="Top" HorizontalAlignment="Center">
<Image.Source>
<BitmapImage UriSource="{Binding PathCover}" />
</Image.Source>
</Image>
</Border>
<Polygon Points="0,0 0,50, 50,0" Stroke="Red" FillRed" RenderTransformOrigin="0.5,0.5" Visibility="{Binding CurrentPage, Converter={StaticResource BookmarkVisibilityConverter}}" Width="{Binding ActualWidth, ElementName=image}" />
</Grid>
<TextBlock HorizontalAlignment="Center" TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding Title}" Margin="0,10,0,0" Foreground="Black" />
</StackPanel>
</DataTemplate>
So if anyone have the a hint to my problem it'll be great!
You can be use only directory/filename.ext on Image Source, if extracted images, sub directory.
Concat two value and set to PathCover Property:
folder.Name + "/" + cover.Name
And edit Data Templete in this section:
<Image Stretch="Uniform" x:Name="image" VerticalAlignment="Top" HorizontalAlignment="Center" Source={Binding PathCover}/>
Regards.
Simply use String instead of Uri.
in mainpage.xaml
<Image Source="{Binding VehicleIcon}" Height="54" Width="54"/>
in viewmodel.cs file
public String VehicleIcon {get;set; }
...
VehicleIcon = "ms-appx:///Assets/logo.png";