How to add checked contact in list Windows Phone 8? - c#

i am trying to add contacts in list as my code is,
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,10">
<TextBlock x:Name="ContactResultsLabel" Text="results are loading..." Style="{StaticResource PhoneTextLargeStyle}" TextWrapping="Wrap"></TextBlock>
<ListBox x:Name="ContactResultsData" ItemsSource="{Binding listOfContacts}" Height="293" Margin="24,0,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="contactChk" IsChecked="false" Foreground="Black" Background="Black" BorderBrush="White"></CheckBox>
<TextBlock x:Name="ContactResultsName" Text="{Binding Name}" FontSize="50"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
not able to get contacts under list box i am using this method on button click,
private void GetSelectedCheckObjItem()
{
try
{
for (int i = 0; i < ContactResultsData.Items.Count; i++)
{
// Get a all list items from listbox
ListBoxItem ListBoxItemObj = (ListBoxItem)ContactResultsData.ItemContainerGenerator.ContainerFromItem(ContactResultsData.Items[i]);
// find a ContentPresenter of that list item.. [Call FindVisualChild Method]
ContentPresenter ContentPresenterObj = FindVisualChild<ContentPresenter>(ListBoxItemObj);
// call FindName on the DataTemplate of that ContentPresenter
DataTemplate DataTemplateObj = ContentPresenterObj.ContentTemplate;
CheckBox Chk = (CheckBox)DataTemplateObj.FindName("contactChk", ContentPresenterObj);
// get a selected checkbox items.
if (Chk.IsChecked == true)
{
MessageBox.Show(Chk.Content.ToString().Trim());
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I got this method from google it looks fine but issue is that i am not getting "Findname" in this line,
CheckBox Chk = (CheckBox)DataTemplateObj.FindName("contactChk", ContentPresenterObj);
i also tried this one,
<ListBox x:Name="ContactResultsData" SelectionMode="Multiple" ItemsSource="{Binding listOfContacts}" Height="293" Margin="24,0,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="contactChk"
IsChecked={Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}},
Path=IsSelected}"
Foreground="Black" Background="Black" BorderBrush="White">
</CheckBox>
<TextBlock x:Name="ContactResultsName" Text="{Binding Name}" FontSize="50"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
On using this i am not getting these properties,
Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}
and properties i am getting are,
Self and TemplatedParent
Is there any alternative for adding contact in list. Well i am alerting on checkbox click,
private void contactChk_Checked(object sender, RoutedEventArgs e)
{
CheckBox chk2 = (CheckBox)sender;
MessageBox.Show("" + chk2.IsChecked);
count++;
}
perhaps i can add contact in list from this method
Hopes for your suggestion
Thanks

using Microsoft.Phone.UserData;
//Use this name space
FOllow the below //improvise a little bit
Contacts cons = new Contacts();
foreach(var c in con)
{
a.cnts.Add(new Contactss()
{
name=c.name,
number=c.phone
});
}
lstbxk.ItemsSource = a.cnts;

Related

Selecting a listview row with a checkbox

I'm calling an api into a WPF listView. I added a CheckBox to each row and am trying to select a row the CheckBox and then display that value.
My xaml file:
<ListView x:Name="myListView"
SelectedValue="{Binding title}"
Height="550" Margin="35,149,-202.2,0"
VerticalAlignment="Top"
Background="AntiqueWhite" Grid.ColumnSpan="2"
SelectionChanged="MyListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<CheckBox
Name="myCheckBox"
Click="listView_Click"
IsChecked="{Binding IsChecked}"
Margin="5, 0"/>
<TextBlock Text=" " />
<TextBlock Text="{Binding title}" />
<TextBlock Text=", " />
<TextBlock Text="{Binding publisher}" />
<TextBlock Text=", " />
<TextBlock Text="{Binding price}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And my listView_Click method, with what I've tried and the output it produced
private void listView_Click(object sender, RoutedEventArgs e)
{
//Selected_label.Text = myListView.ItemsSource.ToString();
//Output = System.Collections.Generic.List`1[ShortBoxedUI.ShortBoxed+Comics]
//Selected_label.Text = myListView.Items.ToString();
//Output = System.Windows.Controls.ItemCollection
//Selected_label.Text = myListView.ToString();
//Output = System.Windows.Controls.ListView Items.Count:352
}
I checked the past questions/answers and didn't find anything that aligned with what I'm trying to do.
By default, the DataTemplate in ListView.ItemTemplate will bind to the data item from ItemsSource. If you want to bind to the ListViewItem itself (which is housing the DataTemplate), you can use RelativeSource:
...
IsChecked="{Binding IsSelected,
RelativeSource={RelativeSource AncestorType=ListViewItem}}"
...
The correct property to get the currently selected item is SelectedItem, while SelectedValue would only be used in conjunction with SelectedValuePath.
And the event for doing something when the selected item changes is SelectionChanged.
private void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MyDataObject selectedItem = myListView.SelectedItem;
Selected_label.Text = selectedItem.SomeTextProperty;
}
Commonly, though, you would bind to SelectedItem rather than handle SelectionChanged directly.

Wpf listview where listviewitem is a custom button

I have a problem. I have a list view in my xaml:
<ListView
Margin="0 10 0 0"
DockPanel.Dock="Top"
ItemsSource="{Binding Items}"
ScrollViewer.VerticalScrollBarVisibility="Hidden"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
BorderThickness="0"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<local:ItemView/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
My item view looks like this (which is in UserControl tag):
<buttons:MyButton
cal:Message.Attach="DoSomething">
<buttons:MyButton.Visual>
<DockPanel
HorizontalAlignment="Left">
<local:Image
DockPanel.Dock="Left"
CountryCode="{Binding Source}"/>
<TextBlock
DockPanel.Dock="Left"
VerticalAlignment="Center"
Padding="15 0 0 0"
FontFamily="{StaticResource MediumFont}"
FontSize="16"
Foreground="{StaticResource DarkText}"
Text="{Binding TextValue}" />
</DockPanel>
</buttons:MyButton.Visual>
</buttons:MyButton>
Now the problem is that when i click on the list item, my selectedItem is not set. It always null unless I click on the very edge of the list item, then it sets the selected value, but i have to click again in the middle of the item to call the action I want.
My question is: How can I make my list view item on click (on the whole item plot) set the selected item and call the action I want?
P.S. I am using Caliburn Micro if this helps...
If you don't mind using code behind or a view model, you could do something like this:
<ListView.ItemTemplate>
<DataTemplate>
<Button BorderBrush="Transparent" Background="Transparent" Focusable="False">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding DataContext.ClickCommand, ElementName=ListViewName}" CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<!-- YOUR TEMPLATE HERE -->
<Button.Template>
</DataTemplate>
</ListView.ItemTemplate>
This is a view/control related thing. You could handle the Click event for the Button and explicitly set the IsSelected property of the parent ListViewItem container like this:
private void OnClick(object sender, RoutedEventArgs e)
{
var listViewItem = FindParent<ListViewItem>(sender as DependencyObject);
if (listViewItem != null)
listViewItem.IsSelected;
}
private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
}
XAML:
<ListView.ItemTemplate>
<DataTemplate>
<local:ItemView ButtonBase.Click="OnClick"/>
</DataTemplate>
</ListView.ItemTemplate>
Or you could set the SelectedItem property of the ListView to the DataContext of the element:
private void OnClick(object sender, RoutedEventArgs e)
{
FrameworkElement fe = sender as FrameworkElement;
if (fe != null)
listView.SelectedItem = fe.DataContext;
}
XAML:
<ListView x:Name="listView" ... />
I know this is an old question, but what I think you were looking for is something like this
<ListView ItemsSource="{Binding ListViewItemTemplates}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<Button x:Name="StartPage">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<cal:Action.Target>
<cal:ActionMessage MethodName="StartPage">
<cal:Parameter Value="{Binding}" />
</cal:ActionMessage>
</cal:Action.Target>
</i:EventTrigger>
</i:Interaction.Triggers>
<Button.Template>
<ControlTemplate>
<StackPanel Width="210" Orientation="Horizontal">
<Image Source="{Binding Path=Source}"
Stretch="None" />
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</ControlTemplate>
</Button.Template>
</Button>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
<ListView/>
Then you can easily bind this with the following
private ObservableCollection<ListViewItemTemplate> listViewItemTemplates;
public ObservableCollection<ListViewItemTemplate> ListViewItemTemplates
{
get => listViewItemTemplates;
set
{
listViewItemTemplates = value;
this.OnPropertyChanged("ListViewItemTemplates");
}
}
Where ListviewItemTemplate is a class consisting of two strings Name and Source

Combobox SelectedItem and Binding in UWP

Currently Developing an UWP Application having troubles with comboboxes.
I am binding an ObservableCollection to a combobox (it works)
var WarehouseList = new ObservableCollection<Warehouse>(taskmag.Result);
WarehouseBox.ItemsSource = WarehouseList;
What I would like to do is to show a selecteditem when I load data into my form.
I am not using MVVM and this is my Combox XAML
<ComboBox HorizontalAlignment="Stretch" Width="400" FontSize="32" Name="WarehouseBox" Margin="20,0,0,0">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="Auto" Height="Auto">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding WarehouseID}" Name="MID" Visibility="Collapsed"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
I have no idea where to start from as documentation always implies MVVM or some other thing I have not implemented.
I am willing to change my items coll to List or IEnumerable if it can help solve the issue.
Any help is greatly appreciated.
Here's the full thing, let me know if it still doesn't work for you:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ComboBox x:Name="ComboBoxWarehouses">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="Auto" Height="Auto">
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
public MainPage()
{
this.InitializeComponent();
var items = new ObservableCollection<Warehouse>();
var item = new Warehouse() {Name = "selected"};
items.Add(new Warehouse() { Name = "not selected"});
items.Add(item);
items.Add(new Warehouse() { Name = "Another Not Selected"});
ComboBoxWarehouses.ItemsSource = items;
ComboBoxWarehouses.SelectedItem = item;
}

Command of Listbox inside long list selector not firing - Windows phone 8 - MVVM

I am creating custom phone book which reads phone book contacts and displays inside my application. So I am creating a long list selector and a listbox inside it.
My listbox will contain phone contact name and list of phone number with the check box under the particular name. I wrote an event trigger inside my listbox to make track of the checkbox is clicked or not.
PROBLEM : Event is not firing in the view model. I suspect since the listbox is present inside another list(long list selector), event is not firing.
Here is xaml code:
<phone:LongListSelector Grid.Row="3" LayoutMode="List" ItemsSource="{Binding PhoneBookDataSource}" IsGroupingEnabled="True" HideEmptyGroups="True">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" >
<TextBlock Text="{Binding PhoneContactName}" FontWeight="SemiBold" FontSize="36" Foreground="Green"></TextBlock>
<ListBox ItemsSource="{Binding LstPhoneContactNumber,Mode=TwoWay}" ScrollViewer.VerticalScrollBarVisibility="Disabled" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<i:InvokeCommandAction Command="{Binding PhoneNumberCheckedStateChangeCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="480">
<TextBlock Text="{Binding PhoneNumberItem}" FontSize="25" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="Gray"></TextBlock>
<CheckBox Foreground="Black" Background="Black" VerticalAlignment="Center" HorizontalAlignment="Right" IsChecked="{Binding IsPhoneNumberItemChecked,Mode=TwoWay}"></CheckBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
<phone:LongListSelector.GroupHeaderTemplate>
<DataTemplate>
<Border Background="Transparent" Padding="5">
<Border Background="{StaticResource PhoneAccentBrush}" BorderBrush="{StaticResource PhoneAccentBrush}" BorderThickness="2" Width="62"
Height="62" Margin="0,0,18,0" HorizontalAlignment="Left">
<TextBlock Text="{Binding Key}" Foreground="{StaticResource PhoneForegroundBrush}" FontSize="48" Padding="6"
FontFamily="{StaticResource PhoneFontFamilySemiLight}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Border>
</Border>
</DataTemplate>
</phone:LongListSelector.GroupHeaderTemplate>
<phone:LongListSelector.JumpListStyle>
<Style TargetType="phone:LongListSelector">
<Setter Property="GridCellSize" Value="113,113"/>
<Setter Property="LayoutMode" Value="Grid" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border Background="{Binding Converter={StaticResource BackgroundConverter}}" Width="113" Height="113" Margin="6" >
<TextBlock Text="{Binding Key}" FontFamily="{StaticResource PhoneFontFamilySemiBold}" FontSize="48" Padding="6"
Foreground="{Binding Converter={StaticResource ForegroundConverter}}" VerticalAlignment="Center"/>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</phone:LongListSelector.JumpListStyle>
</phone:LongListSelector>
Here is my view model:
public DelegateCommand PhoneNumberCheckedStateChangeCommand { get; set; }
public DelegateCommand SendSMSCommand { get; set; }
public CustomPhoneBookViewModel(INavigationService nav, IDataService data, IAESEnDecrypt encrypt, IGeoLocationService geoLocation, IMessageBus msgBus, ISmartDispatcher smartDispatcher)
: base(nav, data, encrypt, geoLocation, msgBus, smartDispatcher)
{
IsProgressBarBusy = true;
PhoneContactsList = new ObservableCollection<PhoneBookEntity>();
PhoneBookDataSource = new ObservableCollection<LLSAlphaKeyGroup<PhoneBookEntity>>();
InitializeDelegateCommands();
GetDeviceResolution();
ReadPhoneBook();
}
private void OnPhoneNumberItemCheckedStateChangedCommand()
{
try
{
foreach (var parentItem in PhoneBookDataSource)
{
foreach (var childItem in parentItem)
{
foreach (var item in childItem.LstPhoneContactNumber)
{
if (item.IsPhoneNumberItemChecked)
IsSendSMSButtonEnabled = true;
return;
}
}
IsSendSMSButtonEnabled = false;
}
}
catch { }
finally
{
SendSMSCommand.RaiseCanExecuteChanged();
}
}
Any suggestions is appreciated!!
The easiest way of making the nested ListBox interaction bind to the global ViewModel (instead of to its own, nested DataContext) is to assign a unique name to the outmost LongListSelector:
<phone:LongListSelector x:Name="OuterList" Grid.Row="3" LayoutMode="List" ItemsSource="{Binding PhoneBookDataSource}" IsGroupingEnabled="True" HideEmptyGroups="True">
and explicitly bind the Command to this element's DataContext (which is the global ViewModel):
<i:InvokeCommandAction Command="{Binding ElementName=OuterList, Path=DataContext.PhoneNumberCheckedStateChangeCommand}" />

Xaml - Bind listviewitem source object

I use an observableCollecion in my VM. This Collection is bind into my view in a ListView. In my items I try to get the element who create this item. Add it in my commandParameter and do the thing.
Here's my VM :
public RelayCommand<SelectionCommandParameter> CmdRemoveFromQuiz { get; set; }
public ObservableCollection<Question> SelectedQuiz
{
get { return _selectedQuiz; }
set
{
_selectedQuiz = value;
RaisePropertyChanged("SelectedQuiz");
}
}
private void RemoveFromQuiz(SelectionCommandParameter selection)
{
if (selection.Parameter is Question)
{
ObservableCollection<Question> tempQuiz = SelectedQuiz;
Question _question = (Question)selection.Parameter;
tempQuiz.Remove(_question);
SelectedQuiz = tempQuiz;
}
}
The problem start with the RemoveBtn I start the command, and selection stay null I want to get the ObservableCollection<Question> object use in my ListViewitem
Now My View :
<userControls:CharmFlyout
x:Name="cfoQuizList"
x:Uid="QuizListCreatingPageFlyout"
Heading="Question Multiple"
HorizontalAlignment="Left"
Grid.Column="0"
Grid.RowSpan="2"
Style="{StaticResource stlAddRecipientFlyout}">
<tut:TutorialAwareListView x:Name="gvQuizItem"
ItemsSource="{Binding SelectedQuiz}"
IsItemClickEnabled="True"
CanReorderItems="True"
SelectionMode="None"
ManipulationMode="TranslateRailsX">
<ListView.ItemTemplate>
<DataTemplate x:Name="DTQuizItem">
<Grid HorizontalAlignment="Left" Width="{StaticResource RectangleTileWidth}" Height="{StaticResource RectangleTileHeight}"
Margin="0 0 0 0" Background="{StaticResource OrangeBackgroundThemeBrush}">
<Grid Grid.Column="1">
<Button x:Name="RemoveBtn" Content="X" HorizontalAlignment="Right" VerticalAlignment="Top" Width="40" Height="40"
BorderThickness="0" Command="{Binding DataContext.CmdRemoveFromQuiz, ElementName=gvQuizItem}" CommandParameter="{Binding Question}"/>
<maxCtrls:MaxAutoScrollingContentPresenter VerticalAlignment="Center"
ScrollingDuration="{Binding Name, Converter={StaticResource TextToTimeToReadShortFormatConverter}}"
ScrollingBeginTime="0:0:2">
<TextBlock Text="{Binding Name}" FontWeight="SemiBold"
Foreground="{StaticResource WhiteBackground}"
Margin="20,5,10,5" VerticalAlignment="Center" TextWrapping="Wrap"/>
</maxCtrls:MaxAutoScrollingContentPresenter>
</Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</tut:TutorialAwareListView>
</userControls:CharmFlyout>
The TutorialAwareListView Work exactly like a ListView. I use it juste to point the element while the tutorial is running.
It's a Windows Store App !! I can't do all the thing we would like to.
You should change your SelectionMode="None" to Single or Multiply.
And make new ObservableCollection for selected items. You bind just ItemsSource="{Binding SelectedQuiz}". Bind SelectedItems="{...}"

Categories

Resources