I am using Listpicker to allow users to select color.
So i used a Toolkit Listpicker with a DataTemplate that includes Textbox to display its list items. What I want is when the page loads, the previously selected color(item) gets automatically selected. But it is giving me an obvious 'System.InvalidOperationException' exception because the items are not added simply but via datatemplate textbox. Please help me :
<toolkit:ListPicker x:Name="BackgroundColor" FullModeHeader="Select Background Color:" Header="Background Color:" BorderThickness="0" FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}" ItemTemplate="{StaticResource PickerItemTemplate}" Background="#FF09043C" SelectionChanged="BackgroundColor_SelectionChanged" >
</toolkit:ListPicker>
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Name="PickerItemTemplate">
<TextBlock Text="{Binding BackGroundColorString}" />
</DataTemplate>
<DataTemplate x:Name="PickerFullModeItemTemplate" >
<Grid x:Name="rootGrid" Margin="0">
<StackPanel Orientation="Horizontal">
<TextBlock Name="BackgroundColor"
Text="{Binding BackGroundColorString}"
/>
</StackPanel>
</Grid>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
if (SunderGutkaSettings.Contains(SG_KEY_BACKGROUNDCOLOR)) //check if key is not present, read value
{
if (BackGroundColorList.Count != 0)//test if list if not empty
{
var ListPickerBackGroundColorRead = BackGroundColorList[singletonInstance.SelectedFontColorIndex] as BackGroundlistPickerClass; //pull whole class
string ListPickerBackGroundColorReadString = ListPickerBackGroundColorRead.BackGroundColorString;
int ListPickerBackGroundColorReadStringToIndex = BackGroundColorList.FindIndex(x => x.BackGroundColorString.StartsWith(ListPickerBackGroundColorReadString));
BackgroundColor.SelectedIndex = ListPickerBackGroundColorReadStringToIndex; //DISABLE FOR testing
}
Actually, on simplyfing my code :
BackgroundColor.SelectedIndex = 0; Doesnt work
nor does
BackgroundColor.SelectedItem="Red";
Help me
To Set the Item,
This.BackgroundColor.SelectedItem = YourObject;
This is how you get selecteditem of ListPicker, probably you need to cast to the object you bind to the list Picker
private void BackgroundColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = (sender as ListPicker).SelectedItem;
}
Related
I'm loading data from an xml file into a listbox . Here is my xaml
<ListBox x:Name="lstSearchCategory" FontFamily="Arial Black"
VerticalAlignment="Center" Margin="25,69,19,10" Height="264">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel >
<Image Source="{Binding Image}" Height="100" Width="100"
HorizontalAlignment="Left"></Image>
<TextBlock HorizontalAlignment="Right" Text="{Binding Name}"
FontSize="30" Foreground="Black" Margin="140,-100,0,0"/>
<TextBlock Text="{Binding Category}" FontSize="24"
Foreground="Black" Margin="10,-10,0,0"/>
<TextBlock Text="{Binding Price}" HorizontalAlignment="Right"
Foreground="Red" Margin="300,-25,0,16"/>
<Rectangle Width="500" Fill="Black" Height="0.5"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This is working fine. Now I want that when I select any listbox item, I get its respective values i.e image, price, category etc. How can i do this ? Help
You need to get the selected item in a ListBox Event and get the DataTemplate from the ListBox (as seen on MSDN):
private void lstEvents_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lbi = (lstEvents.ItemContainerGenerator.ContainerFromIndex(lstEvents.SelectedIndex)) as ListBoxItem;
ContentPresenter cp = GetFrameworkElementByName<ContentPresenter>(lbi);
DataTemplate dt = lstEvents.ItemTemplate;
Label l = (dt.FindName("lblEventId", cp)) as Label;
MessageBox.Show(l.Content.ToString());
}
You need generate Tap = "lstSearchCategory_Tap" in your XAML file and below code in .cs file
private void lstSearchCategory_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
try
{
ListBox ListBoxSelecteditem = (ListBox)sender;
YourModel model = (YourModel)ListBoxSelecteditem.SelectedItem;
string name = model.Name;
string cat = model.Category;
.......
string ControlName = ((System.Windows.FrameworkElement)
(((System.Windows.RoutedEventArgs)(e)).OriginalSource)).Name;
if (ControlName.ToLower() != "name".ToLower())
{
}
}
catch (Exception ex)
{ }
}
try this
<ListBox Tap="lstSearchCategory_Tap" x:Name="lstSearchCategory">
and than on tap event add this
var selected = (classname)lstSearchCategory.SelectedValue;
MessegeBox.Show(selected.Name + selected.Price);
here class-name is name of class where you are binding the name, price etc values
If you fill your ListBox via binding, you should have some property lile SelectedItem in your view model. So the currently selected item should always be stored in the viewmodel for easy access. Just add a binding to SelectedItem in your viewmodel and every thing should work.
I have listbox which contains one textblock and another checkbox.
In xaml file it looks something like this:
<ListBox x:Name="notificationSettingsListBox" Grid.Row="1" Margin="20,20,20,20" Background="#e79e38" SelectionChanged="notificationSettingsListBox_SelectionChanged" Tap="notificationSettingsListBox_Tap">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="#055cc3" Width="500" Height="200" Margin="30,40,30,20">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding channel_name}" Foreground="White" FontSize="31" TextAlignment="Left" TextWrapping="Wrap" Margin="0,20,10,0" />
<CheckBox Name="pushNotiOnCheckBox" Content="Enable Notification" IsChecked="false" Foreground="White" Background="White" BorderBrush="White" Checked="pushNotiOnCheckBox_Checked" Unchecked="pushNotiOnCheckBox_Unchecked"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now whenever user checks any checkbox i need the index of the checkbox.
I want the index from the inside of this method:
private void pushNotiOnCheckBox_Checked(object sender, RoutedEventArgs e)
{}
How can I achieve that in Windows phone?
Assuming that you have List<T> in the ListBox.ItemsSource, then you can use IndexOf() method to get the index of the underlying model in the ItemsSource, which corresponds to the index of the CheckBox in the ListBox :
private void pushNotiOnCheckBox_Checked(object sender, RoutedEventArgs e)
{
//get the checkbox that corresponds to current checked event
CheckBox chk = (CheckBox)sender;
//get the underlying model object from DataContext
MyModel model = (MyModel)chk.DataContext;
//get the entire models used to populate the ListBox
var models = (List<MyModel>)notificationSettingsListBox.ItemsSource;
//find index of current model in the models list,
//which should be the same as checkbox index you want
var index = models.IndexOf(model);
}
You can do this with ItemContainer Style.
<ListBox SelectedIndex={Binding Index,Mode=Twoway}>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected"
Value="{Binding IsOperationSelected,Mode=TwoWay}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
And in you need to change your CheckBox.IsChecked to Binding Like this
<CheckBox Name="pushNotiOnCheckBox" Content="Enable Notification" IsChecked="{Binding IsOperationSelected,Mode=TwoWay}" Foreground="White" Background="White" BorderBrush="White" Checked="pushNotiOnCheckBox_Checked" Unchecked="pushNotiOnCheckBox_Unchecked"/>
I have a web browser which is storing all the visited websites. There is just one issue, I would like it for the user to click on one of the records and then it should open in the webbrowser.
Once the user has navigated to a page, this method is called with the url:
public List<String> urls;
public string selectedURL;
public MainPage()
{
InitializeComponent();
listBox.DataContext = urls;
}
private void getHistory(string url)
{
urls.Add(url);
listBox.DataContext = null;
listBox.DataContext = urls;
}
private void listBoxtrend_Tap(object sender, GestureEventArgs e)
{
selectedURL = "";
var selected = listBox.SelectedValue as Item;
selectedText = selected.ItemString;
MessageBox.Show(selectedURL);
browserSearch(selectedURL);
}
This is then displayed into a textblock on a pivot page:
<phone:Pivot Margin="0,0,0,0">
<phone:PivotItem Header="" Margin="0,-104,0,0">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="72"/>
<RowDefinition Height="696"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="#FF5E667B" >
</Grid>
</phone:PivotItem>
<phone:PivotItem Margin="0,-104,0,0" Header="">
<Grid>
<ListBox ItemsSource="{Binding Item}" Foreground="RoyalBlue" Name="listBox"
TabIndex="10" Tap="listBox_Tap" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock TextWrapping="Wrap" FontSize="26" HorizontalAlignment="Left"
x:Name="txtHistory" Text="{Binding ItemString}"
VerticalAlignment="Top" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</phone:PivotItem>
</phone:Pivot>
I have tried to put a click event, but there is one way to tell which record is being clicked. Is there a way to use the SelectionChanged event handler. And is there a better way to store this data, maybe in a array or list which then can be saved to IsolatedStorage.
Thank you in advance :)
If you need any more details please comment and I will be happy to explain in further detail :)
It's better if you would have the data you're going to display within a Listbox, I mean the Url's. So that you could easily get whatever the data you want from the clicked item. Make sure that you bind the source for your Listbox.
your xaml:
<ListBox ItemsSource="{Binding Item}" Foreground="RoyalBlue"
Height="395" HorizontalAlignment="Center"
Margin="12,111,0,0" Name="listBox"
VerticalAlignment="Top" Width="438"
TabIndex="10" Tap="listBox_Tap" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock TextWrapping="Wrap" FontSize="26" HorizontalAlignment="Left"
x:Name="txtHistory" Text="{Binding ItemString}"
VerticalAlignment="Top" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And then from your tap event handler of the Listbox
private async void listBoxtrend_Tap(object sender, GestureEventArgs e)
{
selectedText = "";
var selected = listBox.SelectedValue as Item;
selectedText = selected.ItemString;
MessageBox.Show(selectedText);
await Launcher.LaunchUriAsync(new Uri("give the url"));//here should be the selectedText
}
These can be referable for more:
Getting selected value of listbox windows phone 7
LIstbox Selected Item content to textblock
Hope it helps!
I have a report to fill in that is made up of a List of sections, each of which has a List of questions. My current implementation uses a Pivot control whose ItemsSource is set to the List of sections and DataTemplate is a LongListSelector whose ItemsSource is set to the List of questions.
When the user attempts to submit the report, I loop through all the questions to check their validity. If any come back invalid, a flag is set and an error message is shown next to that question.
I would like to be able to focus on the first question that has that flag set but cannot figure out how to obtain a reference to the required LongListSelector so that I can call it's ScrollTo method.
Code:
View
<phone:Pivot toolkit:TurnstileFeatherEffect.FeatheringIndex="0"
Name="QuestionPivot"
ItemsSource="{Binding Sections, Mode=TwoWay}">
<phone:Pivot.Title>
<TextBlock>
<Run Text="{Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}"/>
<Run Text=" "/>
<Run Text="{Binding Path=LocalizedResources.DailyReport, Source={StaticResource LocalizedStrings}}"/>
<Run Text=" - "/>
<Run Text="{Binding ProjectName}"/>
</TextBlock>
</phone:Pivot.Title>
<phone:Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding SectionName}"/>
</DataTemplate>
</phone:Pivot.HeaderTemplate>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<phone:LongListSelector ItemsSource="{Binding Questions, Mode=TwoWay}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0 0 0 20">
...
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
Code Behind (including my failed attempt to cast the SelectedItem to a LongListSelector...)
private void FocusOnFirstInvalid(object sender, EventArgs e)
{
int selectedItem = 1;
foreach (ReportDraftSection s in QuestionPivot.Items)
{
foreach(ReportQuestion q in s.Questions)
{
if(q.IsNotValid)
{
QuestionPivot.SelectedIndex = selectedItem;
var l = (LongListSelector)QuestionPivot.SelectedItem;
l.ScrollTo(q);
}
}
selectedItem += 1;
}
}
Any help would be greatly appreciated.
Since Pivot's ItemsSource is a List of Section, QuestionPivot.SelectedItem contains a Section object instead of LongListSelector. You can try to use ItemContainerGenerator to get PivotItem from SelectedItem, then get LongListSelector from PivotItem's Content (not tested yet) :
.......
QuestionPivot.SelectedIndex = selectedItem;
var pivotItem = (PivotItem)QuestionPivot
.ItemContainerGenerator
.ContainerFromItem(QuestionPivot.SelectedItem);
var l = (LongListSelector)pivotItem.Content;
l.ScrollTo(q);
.......
Using MVVM,
I have two listboxes which contains Checkboxes and data is binded from database.
The Items which are checked in first Listbox want to add it in Second listbox.
First ListBox:
<pmControls:pmListBox SelectionMode="Multiple" Grid.Row="1" Margin="3" ItemsSource="{Binding ParcelFacilities}" >
<interactivity:Interaction.Triggers>
<interactivity:EventTrigger EventName="SelectionChanged">
<shared:EventToCommandTrigger Command="{Binding Listbox_SelectionChangeCommand}" />
</interactivity:EventTrigger>
</interactivity:Interaction.Triggers>
<pmControls:pmListBox.ItemTemplate >
<DataTemplate >
<pmControls:pmCheckBox Content="{Binding Title}" Margin="3" Width="200" IsChecked="{Binding checkedParcelFacility}" >
</pmControls:pmCheckBox>
</DataTemplate>
</pmControls:pmListBox.ItemTemplate>
Second ListBox:
<pmControls:pmListBox SelectionMode="Multiple" Grid.Row="1" Margin="3" ItemsSource="{Binding Selected_ParcelFacilities}"
Height="100">
<pmControls:pmListBox.ItemTemplate >
<DataTemplate >
<pmControls:pmCheckBox Content="{Binding Title}" Margin="3" Width="200" ></pmControls:pmCheckBox>
</DataTemplate>
</pmControls:pmListBox.ItemTemplate>
In ViewMOdel:
I have handled SelectionChanged Event For first Listbox and tryied to add checked element to the collection
Named as Selected_ParcelFacilities and Binded it to Second Listbox.
public ParcelViewModel(IModalDialogService modalDialogService, IMessageBoxService messageBoxService)
{
parcelFacilities = new ObservableCollection<Parcel_Facility>();
Selected_ParcelFacilities = new ObservableCollection<Parcel_Facility>();
Selected_ParcelFacilities.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Selected_ParcelFacilities_CollectionChanged);
}
void Selected_ParcelFacilities_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
OnPropertyChanged("Selected_ParcelFacilities");
}
private void Executelistbox_SelectionChangeCommand(EventToCommandArgs args)
{
bool a = checkedParcelFacility;
foreach (Parcel_Facility item in parcelFacilities)
{
if (Selected_ParcelFacilities != null)
{
Selected_ParcelFacilities.Add(item);
}
}
}
But using above code all items from first listbox are adding to second ,
i am not getting how to check wheather its cheked or not.
Please Help.
you can simply bind your second list box to SelectedItems of your first one. this would work with real selection in listbox first.
<ListBox x:Name="second" ItemsSource="{Binding Elementname=first, Path=SelectedItems, Mode=OneWay}"/>
another approach is to use a ICollectionView with filter for your second listbox. the filter simply handle the checkedParcelFacility Property and the second listbox is bind to the ICollectionView.