Trying to learn Win Phone 8, following along an online tutorial. In the tutorial, the guy uses the ListBox to show files, which is working fine for me.
However, I thought we're supposed to use LongListSelector, so I added that; but nothing shows up.
If I put the LongListSelector first in the markup, neither displays when I run the app in the emulator, so I think I'm getting an exception from binding the LongListSelector. I don't understand why though.
It's pretty simple, click a button and read files in a directory, displaying them back.
<StackPanel x:Name="ContentPanel" Margin="12,0,12,0" Grid.Row="1" >
<Button Content="Show files" Click="Button_Click_1"/>
<ListBox x:Name="lb">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
<Image x:Name="img" Source="{Binding Path}" Width="100" Height="100"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<phone:LongListSelector HorizontalAlignment="Left"
x:Name="llsFiles"
ItemTemplate="{StaticResource FilesDataTemplate}"
/>
</StackPanel>
and the LLS template:
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="FilesDataTemplate">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
then the code-behind:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
GetPackageFiles();
}
private async Task GetPackageFiles()
{
//Get the folder where the app is installed on the phone.
var installFolder = Package.Current.InstalledLocation;
var imagesFolder = await installFolder.GetFolderAsync("Images");
var fileList = await imagesFolder.GetFilesAsync();
lb.ItemsSource = fileList;
llsFiles.ItemsSource = fileList.ToList();
}
Try this
//add this declaration
List<FirstList> source = new List<FirstList>();
public class FirstList
{
[DataMember]
public string cItem { get; set; }
public FirstList(string item)
{
this.cItem = item;
}
}
Then to add anything you would just do this.
source.Add(new FirstList(fileList.ToString());
make you sure you have the binding for it
Related
In my Xamarin Forms application I would like to perform a validation on an Entry element when the user focus it out. Using Completed event only works when the user taps "enter" on the keyboard. I tried to use Unfocused but this event triggers while the user is typing on the Entry element and I really do not understand why.
How could I perform a piece of code only when an Entry element is unfocused?
I've 10 ViewCell elements like this one:
<ViewCell >
<StackLayout Orientation="Horizontal" Padding="13, 5" >
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" Spacing="1">
<Label Text="Matricola" VerticalOptions="Center" HorizontalOptions="StartAndExpand" ></Label>
<Entry x:Name="matricola" Text="{Binding Paziente.MatricolaPaziente, Mode=TwoWay}" HorizontalOptions="FillAndExpand" Completed="Entry_Completed" Unfocused="Entry_Completed" ></Entry>
<Label Text="{Binding RegistrationValidator.MatricolaError, Mode=OneWay}" HorizontalOptions="FillAndExpand" TextColor="IndianRed"></Label>
</StackLayout>
</StackLayout>
</ViewCell>
Code behind:
private async void Entry_Completed(object sender, EventArgs e){
// Some code here
}
Moreover the event triggers with unexpected random senders (other Entry elements, always with e.IsFocused == false)
The Entry focus issue inside ListView seems to occur (on second row of the ListView and onwards) on Android (8.1 and 9.0) (Xamarin.Forms 4.5.0.356).
See also "Entry focus issue inside ListView".
As a workaround, use CollectionView (without ViewCell in ItemTemplate).
Sample without Entry focus issue:
<CollectionView>
<CollectionView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>First</x:String>
<x:String>Second</x:String>
</x:Array>
</CollectionView.ItemsSource>
<CollectionView.ItemTemplate>
<DataTemplate>
<Entry Text="collectionview" Focused="Entry_Unfocused" Unfocused="Entry_Unfocused" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Sample with Entry focus issue in ListView on Android (8.1 and 9.0):
<ListView>
<ListView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>First</x:String>
<x:String>Second</x:String>
</x:Array>
</ListView.ItemsSource>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Entry Text="listview" Focused="Entry_Unfocused" Unfocused="Entry_Unfocused" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Codebehind for observing the focus events:
void Entry_Unfocused(object sender, FocusEventArgs e)
{
Debug.WriteLine($"Entry_Unfocused:{e.IsFocused}:");
}
void Entry_Focused(object sender, FocusEventArgs e)
{
Debug.WriteLine($"Entry_Focused:{e.IsFocused}:");
}
I tried with a sample forms like this
<ContentPage.Content>
<StackLayout Spacing="20" Padding="15">
<Label Text="Text" FontSize="Medium" />
<Entry Text="{Binding Item.Text}" d:Text="Item name" FontSize="Small" Unfocused="Entry_Unfocused" Completed="Entry_Completed" />
<Label Text="Description" FontSize="Medium" />
<Editor Text="{Binding Item.Description}" d:Text="Item description" FontSize="Small" Margin="0" />
</StackLayout>
</ContentPage.Content>
And in the code behind:
private void Entry_Unfocused(object sender, FocusEventArgs e)
{
var txt = ((Entry)sender).Text;
DisplayAlert("Info", $"Value of text after entry lost focus : {txt} ", "OK");
}
private void Entry_Completed(object sender, EventArgs e)
{
var txt = ((Entry)sender).Text;
DisplayAlert("Info", $"Value when Enter Key is tapped : {txt} ", "OK");
}
Everything works fine! While looking into your code again, it seems your are in listview. Maybe the problem might come from there.
I believe the Unfocused event gets triggered regardless of focus or unfocus, but the FocusEventArgs on the event should have a bool called IsFocused which should show whether or not the Entry is still focused. Have you tried checking that? It looks like you Unfocused Event Handler just uses a generic EventArgs when it could be using the more specific FocusEventArgs
Unfocused event is raised whenever the Entry loses focus. I make a simple code to test and verify.
Xaml:
<ListView ItemsSource="{Binding list}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Entry Text="{Binding Name}" Unfocused="Entry_Unfocused" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Code:
public partial class EntryPage : ContentPage
{
public ObservableCollection<Person> list { get; set; }
public EntryPage()
{
InitializeComponent();
list = new ObservableCollection<Person>()
{
new Person (){ Name="A"},
new Person (){ Name="B"}
};
this.BindingContext = this;
}
private void Entry_Unfocused(object sender, FocusEventArgs e)
{
}
}
public class Person
{
public string Name { get; set; }
}
I have had a lot of help so far with creating the correct formatting for an ItemsControl panel and appreciate this communities help so far with helping me troubleshoot coding issues.
Im currently at a rather small hurdle where im trying to figure out how to create multiple boxes within the same ItemsControl. Currently the overall view looks like this:
Im a little stumped and would just like a little guidance really as to where to put the other XAML lines.
I need it to look like this:
Here is my code currently (its all nested within a Frame):
<ItemsControl ItemsSource="{StaticResource userDataCollection}" Margin="40,40,40,725" Width="Auto" Height="310">
<!-- Changing Orientation of VirtualizingStackPanel -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- Change header for ItemsControl -->
<ItemsControl.Template>
<ControlTemplate>
<Border Background="{StaticResource CustomAcrylicDarkBackground}">
<StackPanel>
<TextBlock Text="Accounts At A Glance" FontSize="28" Foreground="#b880fc" Padding="12"/>
<ItemsPresenter/>
</StackPanel>
</Border>
</ControlTemplate>
</ItemsControl.Template>
<!-- Template for each card-->
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Width="240" Height="240" Background="Gray" Margin="30,0,0,0" VerticalAlignment="Center" Padding="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Name}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="24"/>
<TextBlock Grid.Row="1" Text="{Binding PayDate}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="14" />
<TextBlock Grid.Row="2" Text="{Binding NumberOfItems}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="14"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I really apologise for this, im trying to learn as much as i can as i go. Im mainly stuggling with the XAML formatting and incorperating learning material into my project :/ Any help would be amazing
I have an alternative approach for your problem. This uses "semi" MVVM approach (browse through the net and study this pattern).
MainPageViewModel.cs
public class MainPageViewModel : INotifyPropertyChanged
{
private ObservableCollection<User> _userCollection;
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<User> UserCollection
{
get => _userCollection;
set
{
_userCollection = value;
NotifyProperyChanged();
}
}
private void NotifyProperyChanged([CallerMemberName]string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void LoadData()
{
UserCollection = new ObservableCollection<User>
{
new User
{
Name = "John Doe",
PayDate = DateTime.Now,
NumberOfItems = 1
},
new User
{
Name = "John Doe 2",
PayDate = DateTime.Now,
NumberOfItems = 1
},
new User
{
Name = "John Doe 3",
PayDate = DateTime.Now,
NumberOfItems = 1
},
};
}
}
The view (got rid of some styling temporarily):
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:App1.ViewModels"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
Loaded="MainPage_OnLoaded">
<Page.DataContext>
<vm:MainPageViewModel/>
</Page.DataContext>
<Grid>
<ScrollViewer>
<ItemsControl ItemsSource="{Binding UserCollection, Mode=TwoWay}" Margin="15" Width="Auto" Height="310">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- Template for each card-->
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Width="200" Height="100" Background="Gray" Margin="15,0,0,0" VerticalAlignment="Center" Padding="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Name}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="24"/>
<TextBlock Grid.Row="1" Text="{Binding PayDate}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="14" />
<TextBlock Grid.Row="2" Text="{Binding NumberOfItems}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="14"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Page>
View's code-behind:
namespace App1
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
}
public MainPageViewModel VM => (MainPageViewModel) DataContext;
private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
VM.LoadData();
}
}
}
Output:
Next steps:
Apply your styling. Study how to limit grid columns.
Improve the code
further, in MVVM you shouldn't really have implementations on the
code-behind, so study for ICommand, Microsoft.Xaml.Interactivity
Hope this helps.
It perfect now.
Im an idiot.
I essentially needed to seperate the information presented within the UserData.cs Class. I didnt understand how the information was being read but understand it now. The XAML has been left untouched as it works currently for what i need. It will be update to follow the MVVM format as mentioned by Mac. Here is the UserData.CS class located inside a data folder:
using System.Collections.ObjectModel;
namespace BudgetSheet.Data
{
public class UserData
{
public string Name { get; set; }
public string PayDate { get; set; }
public string NumberOfItems { get; set; }
}
class UserDataCollection : ObservableCollection<UserData>
{
public UserDataCollection()
{
// Placeholder, needs to be replaced with CSV or Database information
this.Add(new UserData()
{
Name = "Selected Username",
PayDate = "Friday",
NumberOfItems = "ItemAmount Placeholder"
});
// Placeholder for user 2
this.Add(new UserData()
{
Name = "Selected Username 2",
PayDate = "Friday 2",
NumberOfItems = "ItemAmount Placeholder 2"
});
// Placeholder for user 3
this.Add(new UserData()
{
Name = "Selected Username 3",
PayDate = "Friday 3",
NumberOfItems = "ItemAmount Placeholder 3"
});
}
}
}
Here is what it was before hand and why there were issues with information display:
using System.Collections.ObjectModel;
namespace BudgetSheet.Data
{
public class UserData
{
public string Name { get; set; }
public string PayDate { get; set; }
public string NumberOfItems { get; set; }
}
class UserDataCollection : ObservableCollection<UserData>
{
public UserDataCollection()
{
// Placeholder, needs to be replaced with CSV or Database information
this.Add(new UserData()
{
Name = "Selected Username",
});
// Placeholder for user selected PayDate
this.Add(new UserData()
{
PayDate = "Friday",
});
// Placeholder for user selected PayDate
this.Add(new UserData()
{
NumberOfItems = "ItemAmount Placeholder"
});
}
}
}
This solution does not provide much flexibility currently but it works for the formatting. Marking as resolved to close the ticket
I am following MSDN examples to add a settings page to my first Windows Phone 8 application (warning - I am completely new to XAML, I'm a C++ guy).
The xaml looks like this:
<phone:PhoneApplicationPage
x:Class="PicoSDU.AppSettings"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:PicoSDU"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.Resources>
<local:AppSettings x:Key="PicoSettings"></local:AppSettings>
</phone:PhoneApplicationPage.Resources>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="PicoSDU" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="Settings" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel Margin="30,0,0,0">
<TextBlock Height="36" HorizontalAlignment="Left" Margin="0,0,0,0" Name="txtIpAddress" Text="IP Address" VerticalAlignment="Top" Width="169" />
<TextBox Name="tbIpAddress" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="274"
Text="{Binding Source={StaticResource PicoSettings}, Path=IpSetting, Mode=TwoWay}"/>
<TextBlock Height="36" HorizontalAlignment="Left" Margin="0,0,0,0" Name="txtPort" Text="Port Number" VerticalAlignment="Top" Width="169" />
<TextBox Name="tbPort" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="274"
Text="{Binding Source={StaticResource PicoSettings}, Path=PortSetting, Mode=TwoWay}"/>
<TextBlock Height="36" HorizontalAlignment="Left" Margin="0,0,0,0" Name="txtSysId" Text="System ID" VerticalAlignment="Top" Width="169" />
<TextBox Name="tbSysId" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="274"
Text="{Binding Source={StaticResource PicoSettings}, Path=SysIdSetting, Mode=TwoWay}"/>
<TextBlock Height="36" HorizontalAlignment="Left" Margin="0,0,0,0" Name="txtWsId" Text="Station ID" VerticalAlignment="Top" Width="169" />
<TextBox Name="tbWsId" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="274"
Text="{Binding Source={StaticResource PicoSettings}, Path=WsIdSetting, Mode=TwoWay}"/>
</StackPanel>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
So, pretty simple. four text boxes. It rendered perfectly OK until I added the resource clause
<phone:PhoneApplicationPage.Resources>
<local:AppSettings x:Key="PicoSettings"></local:AppSettings>
</phone:PhoneApplicationPage.Resources>
As soon as I add that the XAML parser throws a wobbler and the root PhoneApplicationPage gets the old blue squiggly and reports our favourite "element is already the child of another element" error. If I remove the resource clause, that error goes away and the xaml renders, but of course the textbox bindings then all throw an error because they cannot see their resources.
I've been googling this the last three hours and I can't see what's wrong, and none of the answers I've found here and elsewhere seem to fit. Can some kind soul show me the blindingly stupid thing I've done and please put me out of my misery?
Edit
Here's the AppSettings class. It's just the Microsoft code sample, hacked into the code-behind:
namespace PicoSDU
{
public partial class AppSettings : PhoneApplicationPage
{
// Our settings
IsolatedStorageSettings settings;
// The key names of our settings
const string IpSettingKeyName = "IpSetting";
const string SysIdSettingKeyName = "SysIdSetting";
const string WsIdSettingKeyName = "WsIdSetting";
const string PortSettingKeyName = "PortSetting";
// The default value of our settings
const string IpSettingDefault = "81.179.24.51";
const string SysIdSettingDefault = "1";
const string WsIdSettingDefault = "511";
const string PortSettingDefault = "1846";
public AppSettings()
{
InitializeComponent ();
try
{
settings = IsolatedStorageSettings.ApplicationSettings;
}
catch (System.IO.IsolatedStorage.IsolatedStorageException e)
{
// handle exception
}
}
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
// If the key exists
if (settings.Contains(Key))
{
// If the value has changed
if (settings[Key] != value)
{
// Store the new value
settings[Key] = value;
valueChanged = true;
}
}
// Otherwise create the key.
else
{
settings.Add(Key, value);
valueChanged = true;
}
return valueChanged;
}
public T GetValueOrDefault<T>(string Key, T defaultValue)
{
T value;
// If the key exists, retrieve the value.
if (settings.Contains(Key))
{
value = (T)settings[Key];
}
// Otherwise, use the default value.
else
{
value = defaultValue;
}
return value;
}
public void Save()
{
settings.Save();
}
public string IpSetting
{
get
{
return GetValueOrDefault<string>(IpSettingKeyName, IpSettingDefault);
}
set
{
if (AddOrUpdateValue(IpSettingKeyName, value))
{
Save();
}
}
}
public string SysIdSetting
{
get
{
return GetValueOrDefault<string> ( SysIdSettingKeyName, SysIdSettingDefault );
}
set
{
if (AddOrUpdateValue ( SysIdSettingKeyName, value ))
{
Save ();
}
}
}
public string WsIdSetting
{
get
{
return GetValueOrDefault<string> ( WsIdSettingKeyName, WsIdSettingDefault );
}
set
{
if (AddOrUpdateValue ( WsIdSettingKeyName, value ))
{
Save ();
}
}
}
public string PortSetting
{
get
{
return GetValueOrDefault<string> ( PortSettingKeyName, PortSettingDefault );
}
set
{
if (AddOrUpdateValue ( PortSettingKeyName, value ))
{
Save();
}
}
}
}
}
Your code is quite bizzare. You are trying to embed one Page (your AppSettings class inherits from PhoneApplicationPage) into another. A much better approach would be to use the MVVM pattern.
Do not make the AppSettings inherit from PhoneApplicationPage and make it into a ViewModel. More info at http://msdn.microsoft.com/en-us/library/windowsphone/develop/gg521153(v=vs.105).aspx
I have changed my code to this:
the view:
<phone:Panorama.ItemTemplate>
<DataTemplate>
<ScrollViewer Width="800" HorizontalContentAlignment="Left" Margin="0,50,0,0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListBox x:Name="list_of_images" ItemsSource="{Binding ImagesUrls}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Width="300" Height="300" Source="{Binding}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ListBox>
<TextBlock Text="{Binding Title}"
Grid.Row="1"
Loaded="TextBlock_Loaded_1"
Margin="50,0,0,0"
FontSize="23"
TextWrapping="Wrap"
Width="360"
HorizontalAlignment="Left"
Foreground="Black"/>
<TextBox Text="{Binding ContactEmail}"
Grid.Row="2"
BorderBrush="Black"
Width="340"
HorizontalAlignment="Left"
BorderThickness="1"
Margin="40,0,0,0"
Foreground="Black" />
<TextBlock Text="{Binding Body}"
Grid.Row="3"
TextWrapping="Wrap"
Foreground="Black"
Margin="50,5,0,0"
Width="360"
HorizontalAlignment="Left"
FontSize="20" />
</Grid>
and I build a new object with different properties, with one of the properties being a list of strings which represents the imageurls, but I cannot get the images to show?
I have attached screenshots, what in my xaml must I change so that I can display the images, cause at the moment it doesn't show any images but it shows all the other details
code for populating collection:
ObservableCollection<ClassifiedAds> klasifiseerd_source = new ObservableCollection<ClassifiedAds>();
ImagesClassifieds new_Classifieds = new ImagesClassifieds();
ObservableCollection<string> gallery_images = new ObservableCollection<string>();
new_Classifieds.Title = klasifiseerd_source[0].Title;
new_Classifieds.ContactEmail = klasifiseerd_source[0].ContactEmail;
new_Classifieds.Body = klasifiseerd_source[0].Body;
foreach (var item in klasifiseerd_source[0].Gallery.Images)
{
var deserialized = JsonConvert.DeserializeObject<GalleryImages>(item.ToString());
gallery_images.Add(deserialized.ImageUrl);
//new_Classifieds.ImageUrls.Add(deserialized.ImageUrl);
}
new_Classifieds.ImageUrls = gallery_images;
// classifiedPanorama.ItemsSource = new_list;
new_Classifieds_list.Add(new_Classifieds);
classifiedPanorama.ItemsSource = new_Classifieds_list;
public class ImagesClassifieds
{
public string Title { get; set; }
public string ContactEmail { get; set; }
public string Body { get; set; }
public ObservableCollection<string> ImageUrls { get; set; }
}
here is the imageurl format, this works (in another par tof my app I simply bind to 1 image in this format and it works perfectly)
Depending on whether you want to just display a list of images or if you also want to be able to select them, you may either choose an ItemsControl or a ListBox. In both case you have to define a DataTemplate that controls how each item is displayed.
<ItemsControl ItemsSource="{Binding Images}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
or
<ListBox ItemsSource="{Binding Images}">
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Then you should think about how you define your item class. Just in case you want to be able to dynamically add or remove images from the list and let the UI be automatically updated, you should use an ObservableCollection as container type. As there is a built-in type conversion from string to ImageSource (the type of the Image control's Source property), you may simply use an ObservableCollection<string>.
public class Gal
{
public ObservableCollection<string> Images { get; set; }
}
You may create an instance of that class like so:
var gallery = new Gal();
gallery.Images = new ObservableCollection<string>(
Directory.EnumerateFiles(#"C:\Users\Public\Pictures\Sample Pictures", "*.jpg"));
Now you may directly bind to that instance by simply setting the DataContext of your Window (or wherever the image list should be shown) to this instance:
DataContext = gallery;
Note the binding declaration in the ItemsControl or ListBox above was {Binding Images}. If you really have to have a property Gallery (which I assume is in MainWindow) and bind like {Binding Gallery.Images} you may set the DataContext like this:
DataContext = this;
so I basically created a loaded event on the listbox and added this code
private void list_of_images_Loaded_1(object sender, RoutedEventArgs e)
{
ListBox lst = (ListBox)sender;
lst.ItemsSource = new_Classifieds_list[0].ImageUrls;
}
which binds the itemssource of the listbox to the list of imageurls. since I cannot access the listbox from codebehind due to it being inside the panorama's itemstemplate
I'm trying to create custom controls derived from the framework controls that have the added functionality of rendering themselves as a TextBlock. I'm doing this because the built-in IsEnabled or IsReadOnly properties don't meet my needs. However, I don't see any overridable methods in the control that would give me the functionality I need.
Am I headed down the right path? If not, is there a better way to do this?
Ok, this example is thrown together - keep that in mind. You'll notice that Im using some telerik controls... but you should be able to get the gist of what im doing. Also, in this example i threw together, im not using a DataTemplateSelector... just selecting the template in the code behind.
Rough sketch of xaml...
<UserControl x:Class="Admin.ManagePositions"
...
Title="MainWindow"
Width="525"
Height="350">
<UserControl.Resources>
<DataTemplate x:Key="ReadPositionTemplate">
<StackPanel>
<TextBlock Text="{Binding PositionCode}" Style="{StaticResource H5}" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<telerik:RadButton x:Name="btnEdit" Content="Edit" Click="btnEdit_Click" Command="{Binding DataContext.EditPositionCommand, ElementName=ucManagePositions}" />
<telerik:RadButton x:Name="btnDelete" Content="Delete Position" Style="{StaticResource AutoSizeButton}" Click="btnDelete_Click" Command="{Binding DataContext.DeletePositionCommand, ElementName=ucManagePositions}" />
</StackPanel>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="EditPositionTemplate">
<StackPanel>
<sdk:Label Target="{Binding ElementName=txtPositionCode}" />
<TextBox x:Name="txtPositionCode" Text="{Binding PositionCode, Mode=TwoWay, ValidatesOnExceptions=True,NotifyOnValidationError=True}" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<telerik:RadButton x:Name="btnSaveEdit" Content="Save" Click="btnSaveEdit_Click" Command="{Binding DataContext.SavePositionCommand, ElementName=ucManagePositions}" />
<telerik:RadButton x:Name="btnCancelEdit" Content="Cancel" Click="btnCancelEdit_Click" Command="{Binding DataContext.ResetHighlightPositionCommand, ElementName=ucManagePositions}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid>
<telerik:RadTransitionControl x:Name="selectedPositionContainer" Loaded="selectedPositionContainer_Loaded" Content="{Binding HighlightedPosition}">
<telerik:RadTransitionControl.Transition>
<telerik:SlideAndZoomTransition />
</telerik:RadTransitionControl.Transition>
</telerik:RadTransitionControl>
</Grid>
</UserControl>
And a rough outline of the code behind:
namespace Admin
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class ManagePositions : UserControl {
public MainWindow()
{
InitializeComponent();
}
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
DataTemplate dt = ucManagePositions.Resources["EditPositionTemplate"] as DataTemplate;
selectedPositionContainer.ContentTemplate = dt;
}
private void btnCancelEdit_Click(object sender, RoutedEventArgs e)
{
DataTemplate dt = ucManagePositions.Resources["ReadPositionTemplate"] as DataTemplate;
selectedPositionContainer.ContentTemplate = dt;
}
private void selectedPositionContainer_Loaded(object sender, RoutedEventArgs e)
{
DataTemplate dt = ucManagePositions.Resources["ReadPositionTemplate"] as DataTemplate;
selectedPositionContainer.ContentTemplate = dt;
}
}
}
Hope that helps!