I am new to windows phone 8 development. I have a set of value in sqlite database. Now want to show all the value in list view.
C#code
Database database = new Database(ApplicationData.Current.LocalFolder, "people.db");
await database.OpenAsync();
string query = "SELECT * FROM PEOPLE";
Statement statement = await database.PrepareStatementAsync(query);
statement.EnableColumnsProperty();
while (await statement.StepAsync())
{
MessageBox.Show(statement.Columns["Name"] );
txt1.Text = statement.Columns["Name"];
}
xaml code:
<ListBox Margin="0,365,0,0" x:Name="mylist1">
<ListBoxItem Height="190">
<TextBlock Width="443" Height="55" x:Name="txt1"></TextBlock>
</ListBoxItem>
</ListBox>
I show the value in message box. but I want to show the value in list view
this method you will going to need in your future code because sometimes you can not access control from thr name because they can be present in data templates..
first make a observablecollection/list of your messages strings and add your strings/texts in it. like this..
public ObservableCollection<string> MessageList { get; set; }
now add value this collection like this..
MessageList = new ObservableCollection<string>();
MessageList.Add(statement.Columns["Name"];);
MessageList.Add(statement.Columns["Name"];);
MessageList.Add(statement.Columns["Name"];);
MessageList.Add(statement.Columns["Name"];);
MessageList.Add(statement.Columns["Name"];);
now in your class contructor set the datacontext of the page..like this.
public AllMessages()
{
this.DataContext = this;
}
now bind set your listbox itemssource in xaml like this..
<ListBox Margin="0,365,0,0" x:Name="mylist1" ItemsSource="{Binding MessageList}">
<ListBoxItem Height="190">
<TextBlock Width="443" Height="55" x:Name="txt1" Text="{Binding}"></TextBlock>
</ListBoxItem>
</ListBox>
You just need to add items too the listbox.
while (await statement.StepAsync())
{
mylist1.Items.Add(statement.Columns["Name"]);
}
Related
I'm Currently Working on a Project Designing a Media Player with a Library Ill post the Code for that Method, What i'm trying to Achieve is using the AutoSuggestionBox To Search through my library GridView items then Querying one of the Songs and highlighting it in the GridView
Here's my Code for the Library
private ObservableCollection<MusicLib> MusicList = new ObservableCollection<MusicLib>();
private StackPanel CurrentTarget;
private string content;
public Browsing()
{
this.InitializeComponent();
}
private async void btn_Add_Click(object sender, RoutedEventArgs e)
{
//Create a new picker
var filePicker = new Windows.Storage.Pickers.FileOpenPicker();
//Add filetype filters.
filePicker.FileTypeFilter.Add(".mp3");
filePicker.FileTypeFilter.Add(".wav");
//Set picker start location to the video library
filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
var files = await filePicker.PickMultipleFilesAsync();
foreach (var file in files)
{
StorageItemThumbnail currentThumb = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 200, ThumbnailOptions.UseCurrentScale);
var albumCover = new BitmapImage();
albumCover.SetSource(currentThumb);
var musicProperties = await file.Properties.GetMusicPropertiesAsync();
var musicname = musicProperties.Title;
var musicdur = musicProperties.Duration;
var artist = musicProperties.Artist;
if (artist == "")
{
artist = "Unkown";
}
var album = musicProperties.Album;
if (album == "")
{
album = "Unkown";
}
MusicList.Add(new MusicLib
{
FileName = musicname,
Artist = artist,
Album = album,
Duration = musicdur,
AlbumCover = albumCover,
MusicPath = file.Path
});
}
}
Here's my Context Menu for Deleting Tracks(It's a Work in Progress i'm Probaly missing something stupid)
private void ListView_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
GridView listView = (GridView)sender;
allContactsMenuFlyout.ShowAt(listView, e.GetPosition(listView));
var a = ((FrameworkElement)e.OriginalSource).DataContext as MusicList;
content = a.text;
}
private void Remove_Click(object sender, RoutedEventArgs e)
{
foreach (var item in MusicList.ToList())
{
if (item.text == content)
{
MusicList.Remove(item);
}
}
content = "";
}
Xaml
<Grid Background="White" Name="MyGrid">
<AutoSuggestBox Name="Search" />
<GridView RightTapped="ListView_RightTapped" Name="mylist" ItemsSource="{x:Bind MusicList}" Margin="0,37,0,0">
<GridView.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel Name="Stacky" PointerEntered="myList_PointerEntered" Orientation="Horizontal">
<Image MaxWidth="100" MaxHeight="100" Source="{Binding AlbumCover}"/>
</StackPanel>
<StackPanel >
<TextBlock Text="{Binding FileName}" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Artist}" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Album}" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Duration}" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FileName}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.Resources>
<MenuFlyout x:Name="allContactsMenuFlyout">
<MenuFlyout.Items>
<MenuFlyoutItem x:Name="Edit" Text="Edit" />
<MenuFlyoutItem x:Name="Remove" Text="Remove" Click="Remove_Click" />
</MenuFlyout.Items>
</MenuFlyout>
</GridView.Resources>
</GridView>
Model
namespace Mp3Player
{
class MusicLib
{
public string FileName { get; set; }
public string Artist { get; set; }
public string Album { get; set; }
public TimeSpan Duration { get; set; }
public string MusicPath { get; set; }
public BitmapImage AlbumCover { get; set; }
}
}
To be more specific on my Question im trying to Query one the object's from my Model to "find" that specific track so like FileName For example
I know with the Auto Suggestion box there are 3 Methods you need to use one of which is a Query Method I'm just at a loss as to what to do so if someone could provide a Example possibly, I Will appreciate it, And Post my Project on GitHub for future Ref for anyone who's new to this like i am .
AutoSuggestBox has been documented with detail of its design and how to use it along with its code examples here.
This is a typical AutoSuggestBox
<AutoSuggestBox PlaceholderText="Search" QueryIcon="Find" Width="200"
TextChanged="AutoSuggestBox_TextChanged"
QuerySubmitted="AutoSuggestBox_QuerySubmitted"
SuggestionChosen="AutoSuggestBox_SuggestionChosen"/>
Backend
private void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
// Only get results when it was a user typing,
// otherwise assume the value got filled in by TextMemberPath
// or the handler for SuggestionChosen.
if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
//Set the ItemsSource to be your filtered dataset
//sender.ItemsSource = dataset;// Here you will filter your music list and only send back the data which matches with the text in your autosuggest box.
}
}
private void AutoSuggestBox_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
{
// Set sender.Text. You can use args.SelectedItem to build your text string.
}
private void AutoSuggestBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
if (args.ChosenSuggestion != null)
{
// User selected an item from the suggestion list, take an action on it here.
}
else
{
// Use args.QueryText to determine what to do.
}
}
In your case you have the collection of MusicLib objects and you need to filter with FileName so the DataSet you send back as filtered data will be from your collection. for that you can use LINQ or just a simple foreach loop if you prefer that.
Note that when you keep filtering your collection but if you change the collection for filtering then you need to keep a second collection as well which will always have all the music tracks,and once you are comfortable with basic concepts, dont hesitate to explore : AdvancedCollectionView by WindowsCommunityToolkit which makes filtering much simpler and powerful for you.
GoodLuck
I've been looking on forums and internet about a custom picker on C#, I have a picker already functional, but some of my research throw me that you are only able to select 1 item of the custom Picker, this is the code im using to deploy the picker.
Picker
<custom:CustomPicker x:Name="pickerCategories" ItemsSource="{Binding listCategoriesName}" SelectedIndex="{Binding SelectedCategory}" SelectedIndexChanged="pickerCategories_SelectedIndexChanged" Grid.Column="1" BackgroundColor="White"/>
the item source are given to the picker as a list of object from a database
is there a way to be able to select multiple index of the custom picker?
for Example...
Picker pk = new Picker(); pk.SelectionMode=Multiple;
For you requirement, you could make a custom Picker renderer in the native uwp project. And then make a new DataTemplate for displaying ComboBox item that contain checkbox in the native control.
<DataTemplate x:Key="templateEmployee" >
<StackPanel Orientation="Horizontal">
<CheckBox Content="{Binding Content,Mode=TwoWay}" IsChecked="{Binding IsCheck,Mode=TwoWay}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</StackPanel>
</DataTemplate>
For CustomPickerRenderer, you should pass the Forms Picker item source to native control(ComboBox). And when combobox drop down closed, you could execute InvokeAction method to send Data to the Forms Picker.
public class CustomPickerRenderer : PickerRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
Control.ItemsSource = e.NewElement.ItemsSource;
Control.ItemTemplate = (Windows.UI.Xaml.DataTemplate)App.Current.Resources["templateEmployee"];
Control.DropDownClosed += Control_DropDownClosed;
}
private void Control_DropDownClosed(object sender, object e)
{
var NewElement = Element as CustomPicker;
var items = (sender as ComboBox).ItemsSource;
NewElement.InvokeAction(items);
}
}
Usage
public MainPage()
{
InitializeComponent();
MyPicker.ItemsSource = new MainViewModel().itemSource;
MyPicker.RegisterAction(IsCheckItems);
}
private List<Item> SelecItms = new List<Item>();
private void IsCheckItems(object data)
{
var items = data as ObservableCollection<Item>;
var str = new StringBuilder();
foreach (var item in items)
{
if (item.IsCheck)
{
SelecItms.Add(item);
str.AppendLine(item.Content);
}
}
SeleitemLabel.Text = str.ToString();
}
And I have uploaded the code sample. Please check.
I have a list like this:
<ListView x:Name="MyList" SelectionMode="None" KeyDown="MyList_KeyDown">
<ListView.Items>
<x:String>Alfa</x:String>
<x:String>Beta</x:String>
<x:String>Gamma</x:String>
</ListView.Items>
</ListView>
In the key down event I want to know which item that is in focus. But since SelectionMode is none, SelectedItem is null. Is there some way to solve this?
You can try something like this:
private void MyList_KeyDown(object sender, KeyRoutedEventArgs e)
{
var inFocus = FocusManager.GetFocusedElement() as ListViewItem;
if(inFocus?.Content != null)
{
//Selected data is now in inFocus.Content
}
}
I'm using the new CarouselView control in my app to display a collection of text/articles. Each article in the collection also contains a string array of text that I refer to as tags. I would like to display these tags horizontally within the carouselview using a control that allows databinding. The expected look should be something like this just below the main text:
Expected look of tags
Any ideas on how I could achieve this?
Well, first the good/bad news: the ListView would allow you to present a bindable set of tags, but unfortunately it does not currently support a Horizontal orientation, so it wouldn't meet your needs.
The next best thing would be a horizontal StackLayout contained within a ScrollView:
<ScrollView Orientation="Horizontal">
<StackLayout x:Key="tags" Orientation="Horizontal">
</StackLayout>
</ScrollView>
And populate that StackLayout with data from the ViewModel when the binding context or that property changes. The example below populates the StackLayout with Label views that are styled up using a style named "TagStyleName".
// Note: If this code doesn't work, someone else wrote it.
protected override OnBindingContextChanged() {
var vm = this.BindingContext as MyViewModelClass;
if (vm == null) return;
vm.PropertyChanged += (o, e) => {
if (e.PropertyName == "Tags") {
WatchTagsForChanges();
RefreshTags();
}
};
}
private void WatchTagsForChanges() {
var vm = this.BindingContext as MyViewModelClass;
if (vm == null) return;
vm.Tags.CollectionChanged += (o, e) => RefreshTags();
}
private void RefreshTags() {
var vm = this.BindingContext as MyViewModelClass;
if (vm == null) return;
this.tags.Children.Clear()
foreach (var tag in vm.Tags) {
this.tags.Children.Add(new Label{ Text = tag, Style = "TagStyleName" }));
}
}
Hi am using xaml file and code given below. I want to get two categories one is current categories and other one is removed categories.If i remove one category it should go to add current category.I don't have any idea about this.so please can any one tell me how to resolve this issue.
<StackPanel>
<TextBlock Text="Current categories"
Style="{StaticResource PhoneTextLargeStyle}"/>
<ListBox x:Name="AddingList" ItemsSource="{Binding name}" SelectionChanged="AddingList_SelectionChanged_1"/>
<TextBlock Text="Removed categories"
Style="{StaticResource PhoneTextLargeStyle}" />
<ListBox x:Name="RemoveList" ItemsSource="{Binding name}" SelectionChanged="RemoveList_SelectionChanged_1"/>
</StackPanel>
my xaml.cs code
private void Button_Click_1(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/CategoriesPage.xaml?" + NotchsList11, UriKind.Relative));
}
I am using edit button, How can i pass listbox item from edit button to categories page and how remove and add listbox items.
My out put want given below image so please help me some one
Few ways of going about this.
One way is to have a single object that has "isRemoved" boolean on it that you just turn on and off. Another way is you could have 2 observablecollections one holding the added, and one holding the removed. so for example:
class:
public class MyData
{
public bool isRemoved { get; set; }
public string Name { get; set; }
}
Use:
ObservableCollection<MyData> AllData = new ObservableCollection<MyData>()
AllData.Add(new MyData(){ isRemoved = true, Name = "Data1"}
AllData.Add(new MyData(){ isRemoved = true, Name = "Data2"}
AllData.Add(new MyData(){ isRemoved = false, Name = "Data3"}
AddingList.ItemsSource = AllData.Where(srch => srch.isRemoved == false);
RemoveList.ItemsSource = AllData.Where(srch => srch.isRemoved == true);
In your Remove button click you just set the isRemoved to true and in your Add you set the isRemoved to false.
or you could use 2 ObservableCollections adding and removing from each.