ListBox item from another ListBox - c#

On my Windows Phone app, i have two ListBox. I need that when keep an item pressed (from ListBox1), the item populates the ListBox2.
So, my LisBox1 is populated from JSON (binding).
The code bellow doesn't works (Error: Value does not fall within the expected range.):
public void addToList2(object sender, System.Windows.Input.GestureEventArgs e)
{
var dcs = ((FrameworkElement)sender).DataContext;
Fields fi = (Fields)dcs;
List2.Items.Add(fi);
}
ListBoxes:
<ListBox Name="List1" Hold="addToList2" ItemsSource="{Binding Items}" Margin="0,85,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="242" />
<ColumnDefinition Width="128" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Margin="0,0,-62,17" Grid.ColumnSpan="3">
<StackPanel.Background>
<SolidColorBrush Color="#FF858585" Opacity="0.5"/>
</StackPanel.Background>
<TextBlock x:Name="NameTxt" Grid.Column="0" Text="{Binding descricao}" TextWrapping="Wrap" FontSize="20" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Grid.Column="1" Text="{Binding valor_preco_a, StringFormat=N2}" TextWrapping="Wrap" Margin="45,20,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<TextBlock Grid.Column="3" Text="{Binding codigo}" TextWrapping="Wrap" FontSize="35" Margin="370,-50,12,0" Style="{StaticResource PhoneTextNormalStyle}" Foreground="Blue"/>
</StackPanel>
<TextBlock Grid.Column="0" Text="R$" Margin="15,48,158,17" Style="{StaticResource PhoneTextSubtleStyle}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
<ListBox Name="List2" HorizontalContentAlignment="Stretch" Grid.ColumnSpan="3" Margin="0,182,-66,0" Visibility="Collapsed">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432" Height="100">
<StackPanel.Background>
<SolidColorBrush Color="#FFE8FF00" Opacity="0.2"/>
</StackPanel.Background>
<TextBlock Grid.Column="0" Text="{Binding descricao}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<Listbox x:Name="listbox1" ItemsSource="{Binding listOneObjects}"
SelectedItem="{listOneSelectedItem}" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="PressAndHold">
<i:InvokeCommandAction Command="{Binding TouchDownCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Listbox>
<Listbox x:Name="listbox2" ItemsSource="{Binding listTwoObjects, Mode=TwoWay}"
SelectedItem="{Binding listTwoSelectedItem, Mode=TwoWay}">
</Listbox>
Your C#
using System.ComponentModel;
public class YourClassName : INotifyPropertyChanged
private List<Object> _listOneObjects;
public List<Object> listOneObjects
{
get{ return _listOneObjects; }
set{ _listOneObjects = value; OnPropertyChanged("listOneObjects"); }
}
private Object _listOneSelectedItem;
public Object listOneSelectedItem
{
get{ return _listOneSelectedItem; }
set{ _listOneSelectedItem = value; OnPropertyChanged("listOneSelectedItem"); }
}
private List<Object> _listTwoObjects ;
public List<Object> listTwoObjects
{
get{ return _listOneObjects; }
set{ _listOneObjects = value; OnPropertyChanged("listTwoObjects "); }
}
private Object _listTwoSelectedItem
public Object listTwoSelectedItem
{
get{ return _listTwoSelectedItem; }
set{ _listTwoSelectedItem= value; OnPropertyChanged("listTwoSelectedItem"); }
}
public ICommand TouchDownCommand{ get{ return _TouchDownCommand; }
private _TouchDownCommand;
public YourClassName(){
this._TouchDownCommand= new ActionCommand(TouchDownExecuted);
}
private void TouchDownExecuted(){
listTwoObjects.clear();
listTwoObjects.Add(listOneSelectedItem);
OnPropertyChanged("listTwoObjects");
}
PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String prop){
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
There are a number of moving parts here so you'll need to know the following.
Databinding
Command Binding
Interaction Triggers
Event Triggers
Binding Modes

object myItem;
public Form1()
{
InitializeComponent();
listBox1.Items.Add("Paul");
listBox1.Items.Add("George");
listBox1.Items.Add("Nik");
}
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
myItem = listBox1.SelectedItem;
listBox2.Items.Add(myItem);
}
Like that you can obtain whatever object is in listbox1 and show it in listbox 2. Just by clicking it with the mouse
Another answer is :
This is worth a read...
http://msdn.microsoft.com/en-us/library/ms171548.aspx
SendKeys.Send("r")
This might just fire once, you may want to attach a timer that starts on the MouseDown event and stops on the MouseUp event. Then you could put the SendKeys in the Timer.Tick event.
private void Form1_Load(object sender, EventArgs e)
{
this.timer1.Interval = 500;
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
timer1.Stop();
this.Text = "moose-Up";
}
private void button1_MouseDown(object sender, EventArgs e)
{
timer1.Start();
this.Text = "moose-Down";
this.richTextBox1.Select();
}
private void timer1_Tick(object sender, EventArgs e)
{
SendKeys.Send("r");
Debug.Print("tickling");
}
Select the control that you wish to receive the SendKeys value...

Related

RadioButton IsChecked not binding to separate variables

I have two radio buttons in a group as part of my XAML project:
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Center" Orientation="Horizontal" Grid.Column="0" Margin="20,0,0,0">
<RadioButton x:Name="XMLViewButton" GroupName="DisplayType" IsChecked="{Binding XmlViewIsChecked, FallbackValue=True, Mode=TwoWay}" Content="XML View" Margin="0,0,5,0"/>
<RadioButton x:Name="TextViewButton" GroupName="DisplayType" IsChecked="{Binding TextViewIsChecked, FallbackValue=False, Mode=TwoWay}" Content="Text View" Margin="5,0,0,0"/>
</StackPanel>
And I then have a command later on which refers to these IsChecked bindings:
public void CopyToClipboard(object o)
{
if (TextViewIsSelected == true)
{
Clipboard.SetText(myFile.TextContent);
}
else if (XmlViewIsSelected == true)
{
Clipboard.SetText(myFile.XMLContent);
}
}
However, the XmlViewIsSelected is permanently True and TextViewIsSelected is always false, no matter which radio button is selected. What am I missing?
I think you are mispelling XmlViewIsChecked with XmlViewIsSelected
The following for me is working
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Center" Orientation="Horizontal" Grid.Column="0" Margin="20,0,0,0">
<RadioButton x:Name="XMLViewButton" GroupName="DisplayType" IsChecked="{Binding XmlViewIsChecked, FallbackValue=True, Mode=TwoWay}" Content="XML View" Margin="0,0,5,0"/>
<RadioButton x:Name="TextViewButton" GroupName="DisplayType" IsChecked="{Binding TextViewIsChecked, FallbackValue=False, Mode=TwoWay}" Content="Text View" Margin="5,0,0,0"/>
<Button Content="Check" Click="Button_Click" />
</StackPanel>
public partial class MainWindow : Window
{
public bool XmlViewIsChecked { get; set; }
public bool TextViewIsChecked { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (TextViewIsChecked)
{
Clipboard.SetText("text");
}
else if (XmlViewIsChecked)
{
Clipboard.SetText("xml");
}
}
}

ListBox.SelectedItem selected wrong row

I create ListBox, wich rows can be editable:
<ListBox Grid.Row="1" x:Name="lbKeys" BorderBrush="Gray"
ItemsSource="{Binding Path=Templates}"
IsSynchronizedWithCurrentItem="True"
Focusable="True"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
HorizontalContentAlignment="Stretch"
ItemContainerStyle="{StaticResource ResourceKey=lbStyle}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="LightGray" Background="WhiteSmoke"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid Name="grEditRow">
<TextBox x:Name="tblbRow" Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"
TextWrapping="Wrap" Margin="2"
Background="Transparent"
HorizontalAlignment="Stretch"
/>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But, when i select row for edit (and i can do it)- i want to delete this row by clicking to button:
<Button x:Name="btDelTemplate" Click="btDelTemplate_Click" Height="22" Width="22"
ToolTipService.ShowOnDisabled="True"
ToolTip="{lang:Link LocalePath=RemoveTemplate,DesignValue='Remove row'}"
>
</Button>
And event handler of it:
if(lbKeys.SelectedItem!=null)
RemoveItem(lbKeys.SelectedItem as Row);
But, selected item often is wrong! As i understand- if i select item by clicking at left border of row- it works well, but when click at textbox inside row- selected item is wrong.
How to fix it?
Thank you!
I find a workaround.
Here the code:
XAML:
<ListBox Grid.Row="1" x:Name="lbKeys" BorderBrush="Gray"
ItemsSource="{Binding Templates}"
IsSynchronizedWithCurrentItem="True"
Focusable="True"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
HorizontalContentAlignment="Stretch"
ItemContainerStyle="{StaticResource ResourceKey=lbStyle}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" BorderBrush="LightGray" Background="WhiteSmoke"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBox x:Name="tblbRow" Text="{Binding Text,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Tag="{Binding}"
GotFocus="tblbRow_GotFocus"
TextWrapping="Wrap" Margin="2"
Background="Transparent"
HorizontalAlignment="Stretch"
/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Key lines:
Tag="{Binding}"
GotFocus="tblbRow_GotFocus"
C# handlers:
private void tblbRow_GotFocus(object sender, RoutedEventArgs e)
{
var textBox = sender as TextBox;
lbKeys.SelectedItem = textBox.Tag;
}
private void btDelTemplate_Click(object sender, RoutedEventArgs e)
{
try
{
foreach (var item in lbKeys.Cast<Row>())
{
if (item.Template.Id == (lbKeys.SelectedItem as Row).Template.Id)
{
_viewModel.RemoveTemplate(item);
break;
}
}
DataContext = _viewModel;
}
catch(Exception ex)
{
throw;
}
}
You can write a handler for GotFocus of the TextBox and change SelectedItem in that programmatically.
--------- Update ----------
private void tblbRow_GotFocus(object sender, RoutedEventArgs e)
{
lbKeys.SelectedItem = (sender as TextBox).DataContext as Row;
}
and you should write some code for Row class to let its objects be comparable:
public class Row
{
public Row() { }
private string _text;
public String Text
{
get
{
return _text;
}
set
{
_text = value;
}
}
public override int GetHashCode()
{
return _text;
}
public bool Equals(Row r)
{
return r._text == _text;
}
public override bool Equals(object r)
{
Row row = r as Row;
return row != null && row._text == _text;
}
}

Binding to ItemsSource not working

I have done the following in XAML
<ItemsControl x:Name="CursorLegendIC" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding}" Margin="0,0" Padding="0,0,0,-300">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<Ellipse Width="8" Height="8" HorizontalAlignment="Left" Margin="0,0,0,-16" Fill="{Binding SeriesColor, Converter={StaticResource ColorToBrushConverter}}" />
<TextBlock Margin="10,0,0,0" HorizontalAlignment="Left" TextWrapping="Wrap" FontSize="11" FontWeight="Bold" Foreground="{Binding SeriesColor, Converter={StaticResource ColorToBrushConverter}}" Text="{Binding SeriesName}"/>
<TextBlock FontSize="11" HorizontalAlignment="Left" TextWrapping="Wrap" Margin="10,-3,0,4" Foreground="{Binding SeriesColor, Converter={StaticResource ColorToBrushConverter}}" Text="{Binding YValue, StringFormat=\{0:0.000\}}" />
<TextBlock FontSize="11" HorizontalAlignment="Left" TextWrapping="Wrap" Margin="10,-8,0,4" Foreground="{Binding SeriesColor, Converter={StaticResource ColorToBrushConverter}}" Text="{Binding RenderableSeries.YAxisId}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
And I have set the data context accordingly:
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
CursorLegendIC.DataContext = this.RolloverSeriesWithoutFirstData;
}
And set the Observable collection property as public
public ObservableCollection<SeriesInfo> RolloverSeriesWithoutFirstData
{
get
{
ObservableCollection<SeriesInfo> Temp = rolloverModifier.SeriesData.SeriesInfo;
return Temp;
}
}
But binding is still not working!
It seems to only take the binding at the first instance.
When data collection is later added, the binding changes does not seem to take effect.
Any help? Thanks
Your issue is that the instance (the entire collection) of the property SeriesInfo changes, without the owner of RolloverSeriesWithoutFirstData (lets call it MyWindow) is notified of the change. Either make your own event, or implemenet INotifyPropertyChanged. I've made an example with INPC:
class SeriesData : INotifyPropertyChanged
{
private ObservableCollection<SeriesInfo> _seriesInfo;
public ObservableCollection<SeriesInfo> SeriesInfo
{
set{ SetProperty(ref _seriesInfo, value); }
}
public event PropertyChangedEventHandler PropertyChanged;
private bool SetProperty<T>(ref T storage, T value, [CallermemberName] string propertyName = null)
{
if(Equals(storage,value)) return false;
storage = value;
var handler = PropertyChanged;
if(handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
return true;
}
}
In MyWindow you does this:
class MyWindow : Window, INotifyPropertyChanged
{
public ObservableCollection<SeriesInfo> RolloverSeriesWithoutFirstData
{
get{ return rolloverModifier.SeriesData.SeriesInfo; }
}
public event PropertyChangedEventHandler PropertyChanged;
public MyWindow()
{
// Get rolloverModifier
rolloverModifier.SeriesData.PropertyChanged += SeriesDataPropertyChanged;
}
private void SeriesDataPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch(e.PropertyName)
{
case "SeriesInfo":
RaisePropertyChanged("RolloverSeriesWithoutFirstData");
break;
}
}
private void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if(handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
Now SeriesData notifies it's listeners (our case MyWindow) that one of it's properties has changed value. MyWindow will then relay that notification to it's listeners (the bindings) that it's property: RolloverSeriesWithoutFirstData has changed.
Assuming that you are using MVVM pattern, you should remove the code behind and just bind to your ObservableCollection :
<ItemsControl x:Name="CursorLegendIC" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding RolloverSeriesWithoutFirstData}" Margin="0,0" Padding="0,0,0,-300">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<Ellipse Width="8" Height="8" HorizontalAlignment="Left" Margin="0,0,0,-16" Fill="{Binding SeriesColor, Converter={StaticResource ColorToBrushConverter}}" />
<TextBlock Margin="10,0,0,0" HorizontalAlignment="Left" TextWrapping="Wrap" FontSize="11" FontWeight="Bold" Foreground="{Binding SeriesColor, Converter={StaticResource ColorToBrushConverter}}" Text="{Binding SeriesName}"/>
<TextBlock FontSize="11" HorizontalAlignment="Left" TextWrapping="Wrap" Margin="10,-3,0,4" Foreground="{Binding SeriesColor, Converter={StaticResource ColorToBrushConverter}}" Text="{Binding YValue, StringFormat=\{0:0.000\}}" />
<TextBlock FontSize="11" HorizontalAlignment="Left" TextWrapping="Wrap" Margin="10,-8,0,4" Foreground="{Binding SeriesColor, Converter={StaticResource ColorToBrushConverter}}" Text="{Binding RenderableSeries.YAxisId}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
+Questions: what is rolloverModifier ? is rolloverModifier.SeriesData.SeriesInfo modified?
You just need to implement the INotifyPropertyChanged Interface in the class that you defined your RolloverSeriesWithoutFirstData property in. As that property has no setter, you will have to manually raise the NotifyPropertyChanged event whenever you update the collection:
(pseudo code):
rolloverModifier.SeriesData.SeriesInfo = DataAccess.GetNewCollection();
NotifyPropertyChanged("RolloverSeriesWithoutFirstData");
Change
CursorLegendIC.DataContext = this.RolloverSeriesWithoutFirstData
for
CursorLegendIC.ItemsSource= this.RolloverSeriesWithoutFirstData
Or as You can see in the above answer, remove code behind and use clear mvvm

Textbox binding with trigger

I need to bind the text box with the data available on it and execute a command associate with that. I want the data entered as well command execution only when "Enter" button on keyboard is pressed. I used to the below code, but it seems, I am getting command execution without "Enter" is pressed also found that for each number or text pressed, I am getting the command. I don't want this to happen.
my InputDataTemplate.xaml code:
<Label Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" Content="{Binding Name}" />
<Label Grid.Column="2" HorizontalAlignment="Left" VerticalAlignment="Center" Content="{Binding Value}" />
<TextBox Grid.Column="1" Width="60" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Data}" DataContext="{Binding}" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged" >
<ei:CallMethodAction TargetObject="{Binding}" MethodName="IpDataTrig" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
I can understand EventName="TextChanged" plays a role here. But not sure about the other stuffs.
My TesterView.xaml code:
<UserControl.Resources>
<DataTemplate x:Key="InputDataTemplate" >
<local:InputDataTemplate DataContext="{Binding}" />
</DataTemplate>
</UserControl.Resources>
<Grid Grid.Row="2" Background="AliceBlue" >
<Label Content="Input Datas" FontWeight="Bold"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
<Border Grid.Row="3" BorderBrush="Black" BorderThickness="0,2,0,0" >
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" >
<ItemsControl x:Name="IpDataNames"
DataContext="{Binding }"
ItemsSource="{Binding IpDataNames}"
ItemTemplate="{DynamicResource InputDataTemplate}" />
</ScrollViewer>
</Border>
my TesterViewModel.cs:
private ObservableCollection<InputDataService> _IpDataNames;
private InputDataService l_IpDataNames;
_IpDataNames = new ObservableCollection<InputDataService>();
public ObservableCollection<InputDataService> IpDataNames
{
get { return _IpDataNames; }
set
{
IpDataNames = value;
}
}
InputDataService.cs:
public class InputDataService : BindableBase
{
public string Name { get; set; }
public string Value { get; set; }
public string Data { get; set; }
public void IpDataTrig()
{
Debug.WriteLine(string.Format("\nInput Data {0} Updated : {1} : {2}", Name, Data, Value));
}
}
Possible duplicate question: https://stackoverflow.com/a/10466285/475727
BTW, nothing is wrong about capturing KeyPress event and calling command from codebehind. It is not violation of MVVM pattern.
Sometimes I use my own behavior implemented as attached property. Big advantage is, that I can use it in styles.
This behaviour update binding source on text property and then calls command. (TextBox.Text binding is updated on losf focus by default)
public static class TextBoxBehaviour
{
public static readonly DependencyProperty CommandOnEnterPressedProperty = DependencyProperty.RegisterAttached("CommandOnEnterPressed",typeof (ICommand),typeof (TextBoxBehaviour),
new FrameworkPropertyMetadata(CommandOnEnterPressedPropertyChanged));
private static void CommandOnEnterPressedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var sender = (TextBox) d;
sender.KeyDown -= OnKeyDown;
if (e.NewValue is ICommand)
{
sender.KeyDown += OnKeyDown;
}
}
private static void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
var tbx = (TextBox) sender;
var textBindigExpression = tbx.GetBindingExpression(TextBox.TextProperty);
if (textBindigExpression != null)
{
textBindigExpression.UpdateSource();
}
var command = GetCommandOnEnterPressed(tbx);
if (command.CanExecute(null)) command.Execute(null);
}
}
[AttachedPropertyBrowsableForType(typeof(TextBox))]
public static void SetCommandOnEnterPressed(TextBox elementName, ICommand value)
{
elementName.SetValue(CommandOnEnterPressedProperty, value);
}
public static ICommand GetCommandOnEnterPressed(TextBox elementName)
{
return (ICommand) elementName.GetValue(CommandOnEnterPressedProperty);
}
}
and usage
<TextBox Text="{Binding SearchTerm, UpdateSourceTrigger=Explicit}"
my:TextBoxBehaviour.CommandOnEnterPressed="{Binding SearchCommand}"/>

How do I bind Phone Contacts in <toolkit:LongListMultiSelector in WP8?

I want to display my phone contacts in LongListMultiSelector. Earlier I was using a list box to display the phone contacts... My implementation was like:
xaml
<ListBox Name="ContactResultsData" ItemsSource="{Binding}" Height="331" Margin="12,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<Border BorderThickness="2" HorizontalAlignment="Left" VerticalAlignment="Center" BorderBrush="{StaticResource PhoneAccentBrush}" >
<Image Source="{Binding Converter={StaticResource ContactPictureConverter}}" Width="48" Height="48" Stretch="Fill" />
</Border>
<TextBlock Name="ContactResults" Text="{Binding Path=DisplayName, Mode=OneWay}" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Margin="18,8,0,0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and C#
private void SearchContacts_Click(object sender, RoutedEventArgs e)
{
ContactResultsData.DataContext = null;
Contacts cons = new Contacts();
cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);
}
void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
try
{
ContactResultsData.DataContext = e.Results;
}
catch (System.Exception)
{
}
}
Now in spite of List Box, i want to display it in a LongListMultiSelector.
How can I do that?
Now I am Using a View Model
public partial class ContactsView : PhoneApplicationPage
{
public ContactsViewModel()
{
var cons = new Microsoft.Phone.UserData.Contacts();
cons.SearchAsync(String.Empty, FilterKind.None, null);
cons.SearchCompleted += ContactsSearchCompleted;
}
private void ContactsSearchCompleted(object sender, ContactsSearchEventArgs e)
{
PhoneContacts = new ObservableCollection<Contact>(e.Results.OrderBy(c => c.DisplayName));
}
private ObservableCollection<Contact> _phoneContacts;
public ObservableCollection<Contact> PhoneContacts
{
get { return _phoneContacts; }
set
{
_phoneContacts = value;
RaisePropertyChanged("PhoneContacts");
}
}
}
How can I bind this viewModel to LongListMultiSelector, so that the ObservableCollection contact data is visible ?
just like the figure ..instead of mail details, i want to show contact details.
Phone Contacts http://blogs.windows.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-53-84-metablogapi/clip_5F00_image010_5F00_41CD2003.png
For the most part, simply replacing all instances of ListBox with phone:LongListSelector works perfectly fine. There are a number of cases where the LongListSelector is not recommended over the ListBox (as some unexpected functionality occurs), but it should work fine.
<phone:LongListSelector ItemsSource="{Binding DataList}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate/>
</phone:LongListSelector.ItemTemmplate>
</phone:LongListSelector>
I modified my view-model as follow:
public class ContactsViewModel : ViewModelBase
{
public ContactsViewModel()
{
Contacts cons = new Contacts();
cons.SearchAsync(String.Empty, FilterKind.None, null);
cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);
}
void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
try
{
PhoneContactsList = new List<Contact>(e.Results.OrderBy(c => c.DisplayName));
System.Diagnostics.Debug.WriteLine("PhoneContacts phone" + PhoneContactsList);
}
catch (System.Exception)
{
//That's okay, no results
}
}
//--------------------------------
private List<Contact> _phoneContactsList;
public List<Contact> PhoneContactsList
{
get { return _phoneContactsList; }
set
{
_phoneContactsList = value;
RaisePropertyChanged("PhoneContactsList");
}
}
}
instead of observablecollection , i am using a list.
and in the xaml, i binded PhoneContactsList to my longlistmultiselector as follow:
<toolkit:LongListMultiSelector x:Name="contactList"
Margin="0,14,-12,0"
ItemsSource="{Binding PhoneContactsList}"
LayoutMode="List"
ItemTemplate="{StaticResource ContactItemTemplate}"
/>
where ContactItemTemplate is as follow:
<DataTemplate x:Key="ContactItemTemplate">
<StackPanel Margin="0,-14,0,24" >
<TextBlock Text="{Binding Path=DisplayName, Mode=OneWay}"
Margin="0,0,0,-4"
FontSize="{StaticResource PhoneFontSizeExtraLarge}"
FontFamily="{StaticResource PhoneFontFamilySemiLight}"/>
<ListBox ItemsSource="{Binding Path=PhoneNumbers}" Height="60" Margin="36,0,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Path=Kind, Mode=OneWay}" />
<TextBlock Grid.Column="1" Text=": " />
<TextBlock Grid.Column="2" Text="{Binding Path=PhoneNumber, Mode=OneWay}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>

Categories