Getting Checkbox index in Windows phone - c#

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"/>

Related

why are the converters being called again?

In my windows phone app one of the pages contains LongListSelector. In that LongListSelector I am using some converters. When the LongListSelector Loaded the Converters are being called as usual. But when I call ScrollTo() method to scroll to a specific item of the LongListSelector, the converters are being called again. Why are the converters being called again? What does ScrollTo() method do that causes converters to be called again?
Sample Code:
XAML:
<phone:LongListSelector ItemTemplate="{StaticResource LLSItemSource}"
Name="ChatListBox">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Background="Transparent"
Visibility="{Binding ID, Converter={StaticResource visibilityConverter}}"
Margin="0,6">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="delete"
Click="ContextMenuItem_Click" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<Border Background="Black"
HorizontalAlignment="Center"
Padding="30,5,30,8"
CornerRadius="20">
<TextBlock Text="{Binding Date, Converter={StaticResource dateStringConverter}}"
Foreground="White"
FontSize="20" />
</Border>
</Grid>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
CS:
private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
{
string header = (sender as MenuItem).Header.ToString();
MessageModel selectedListBoxItem = (sender as MenuItem).DataContext as MessageModel;
if (selectedListBoxItem == null)
return;
if (header == "delete")
{
DeleteItemByID(selectedListBoxItem.ID);
if (ChatListBox.ItemsSource.Count > 0)
{
ChatListBox.ScrollTo(ChatListBox.ItemsSource[delIndex - 1]); // here I am scrolling to the last item that causes converters to be called again
}
}
}
You are written converter for longlistselector items. On loading every item in selector its get executing to convert value on given template

SelectedIndex or SelectedItem of ListPicker with DataTemplate

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;
}

Windows phone 8 saving and open links in web Browser history

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!

How to Make Mutual Exclusive chechkboxs with on checkbox is checked on window loaded in WPF Application

I have three check boxes Namely, Document Submission,Document Pickup and Others. I made this three check Boxes Mutually Exclusive to each other as Below
<Grid Height="303" Width="500">
<ListBox Name="ListBox1" Margin="49,67,86,164">
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<SolidColorBrush
x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="White"/>
</Style.Resources>
</Style>
</ListBox.Resources>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Background="White" IsItemsHost="True"
Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox FontWeight="Bold" FontSize="13" IsThreeState="True" IsChecked="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListBoxItem}}}" Content="{Binding}" BorderThickness="1" AllowDrop="False" Focusable="True" Background="White" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
List Box is Bind on Window loaded as Follows
private void Window_Loaded(object sender, RoutedEventArgs e)
{
List<string> lst = new List<string>();
lst.Add("Documnet Pickup");
lst.Add("Document Submission");
lst.Add("Others");
ListBox1.ItemsSource = lst;
}
How can i make one check box is checked on window loaded. Is this a best approach?.
Since you're binding checkbox IsChecked property to listbox item IsSelected property here :
IsChecked="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListBoxItem}}}"
You can simply set listbox selected index to index of an item, for example, the first item :
List<string> lst = new List<string>();
lst.Add("Documnet Pickup");
lst.Add("Document Submission");
lst.Add("Others");
ListBox1.ItemsSource = lst;
ListBox1.SelectedIndex = 0;
then the respective item will automatically has checkbox checked.
Try adding the last line to your function. It makes the first checkbox checked.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
List<string> lst = new List<string>();
lst.Add("Documnet Pickup");
lst.Add("Document Submission");
lst.Add("Others");
ListBox1.ItemsSource = lst;
ListBox1.Items[0].Selected = true;
}

accessing an item variable from dynamic data in listbox on SelectionChanged

I am populating a listbox from a webcclient, the data is binded to the listbox and not saved anywhere..
Id like to access binded information when the user selects from the listbox
im having trouble accessing the value of a text block from the SelectionChanged event..
<ListBox x:Name="UsersListBox" ItemsSource="{Binding Items}" Height="471" VerticalAlignment="Top" HorizontalAlignment="Left" Width="457" SelectionChanged="TargetsListBox_SelectionChanged" Grid.ColumnSpan="2">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432" Orientation="Horizontal">
<Image x:Name="ImageAddIcon" Source="blkAdd.png" Height="60" Width="71" VerticalAlignment="Stretch" />
<Image x:Name="ImagePointer" Source="blkClick.png" Height="60" Width="71" VerticalAlignment="Stretch" />
<StackPanel>
<TextBlock Name="txtID" Text="{Binding PlayerID}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="#FF8A9A8A" Visibility="Collapsed" />
<TextBlock Name="txtNick" Text="{Binding Nickname}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="#FF8A9A8A" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Id like to access the PlayerID from this dynamicly populated list(from webservice) on a onselected basis
private void TargetsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string ID = UsersListBox.SelectedItem ???PlayerID or txtID???;
}
i just want to get the player id that is binded to the listbox with a selection changed event ANY IDEAS!!!!!!!!! <3
Assuming that "Items" is a ObservableCollection:
private void TargetsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listBox = sender as ListBox;
var selectedItem = listBox.SelectedItem as Player;
if (selectedItem != null)
{
string id = selectedItem.PlayerID
string nick = selectedItem.NickName;
}
}

Categories