WP7 - Call bound number on clicking Listbox item - listbox

So I have a list of objects containing a name and number bound to a listbox in XAML. The listbox displays the number fine, but I want it to call the phone number using phonecall on click. Here is the onlick code:
private void taxiListItem_Click(object sender, RoutedEventArgs e)
{
Microsoft.Phone.Tasks.PhoneCallTask phonecall = new Microsoft.Phone.Tasks.PhoneCallTask();
phonecall.PhoneNumber = "213";
phonecall.Show();
}
and here is where I define the TaxiCompany object that populates the list.
public class TaxiCompany {
public String CoName { get; set; }
public String Phone { get; set; }
public TaxiCompany(String coname, String phone) {
this.CoName = coname;
this.Phone = phone;
}
}
The phone call works fine when I hardcode the number . Now, when I set phonecall.Phonenumber = sender.getPhone() or e.Phone() or any variant of the two, its marked as an undefined method. Am I doing something fundamentally wrong here? I assume object sender or e is the list item being clicked on.
Note: the listbox in the XAML displays both the phone number and address just fine
<Button Click="taxiListItem_Click" Width ="436" Height="120">
<Button.Content>
<StackPanel Orientation="Vertical" Height=" 80">
<StackPanel Orientation="Horizontal" Height="40" Width="436">
<TextBlock Width="436" FontSize="30" Text= "{Binding CoName}" Height="40"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="40" Width="436">
<TextBlock Name ="PhoneNo" Width="300" FontSize="22" Text= "{Binding Phone}" Height="40"/>
</StackPanel>
</StackPanel>
</Button.Content>
</Button>
First time working with C# / Silverlight so any help would be apprecaited.

Try this. The listbox shows the taxi companies and selecting an item in the list causes the phone numbe rot try and be dialed.
Notice that it's not necessary to add buttons to the list and that it's necessary to cast the variables passed to the selection event. (Could also cast the sender to a listbox and then cast the selected item.)
xaml:
<ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding TaxiCompanies}" SelectionChanged="MainListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Height=" 80">
<TextBlock Width="436" FontSize="30" Text= "{Binding CoName}" Height="40"/>
<TextBlock Name ="PhoneNo" Width="300" FontSize="22" Text= "{Binding Phone}" Height="40"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
cs:
// class used for example. Another name would be more appropriate
public class ViewModel
{
public ObservableCollection<TaxiCompany> TaxiCompanies { get; private set; }
public ViewModel()
{
TaxiCompanies = new ObservableCollection<TaxiCompany>();
TaxiCompanies.Add(new TaxiCompany("AAA Cabs", "123-456-789"));
TaxiCompanies.Add(new TaxiCompany("BBB Taxis", "111234329"));
TaxiCompanies.Add(new TaxiCompany("CCC Cars", "98765432"));
}
}
public MainPage()
{
InitializeComponent();
// Set the data context of the listbox control to the sample data
DataContext = new ViewModel();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var phonecall = new PhoneCallTask();
phonecall.PhoneNumber = ((TaxiCompany)(((object[])(e.AddedItems))[0])).Phone;
phonecall.Show();
// Reset selected index to -1 (no selection)
MainListBox.SelectedIndex = -1;
}

Related

Can I populate a Label within my CollectionView with a value outside the ItemsSource List that populates the view?

I have a Label within my CollectionView that I need to populate with a value outside the ItemsSource List that populates the view.
The following code is an example of what I am trying to accomplish but it seems that the CollectionView is limiting the binding context to just the Items list. I have tried naming the label and setting it in my c# code but I cant seem to access the label in c#. I suppose I could build the whole page in c# rather than using the .xaml but unlike this example my actual code uses multiple templates and a template selector. If I could figure this out without rewriting hours of code I would prefer it.
ItemsPage.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="TabTest.Views.ItemsPage"
Title="{Binding Title}"
x:Name="BrowseItemsPage">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Add" Clicked="AddItem_Clicked" />
</ContentPage.ToolbarItems>
<StackLayout Padding="10">
<Label Text="{Binding TestVal}" FontSize="16" HeightRequest="20" />
<!-- ^^^^ This label displays just as expected -->
<RefreshView IsRefreshing="{Binding IsBusy, Mode=TwoWay}" Command="{Binding LoadItemsCommand}">
<CollectionView x:Name="ItemsCollectionView"
ItemsSource="{Binding Items}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Padding="10">
<Label x:Name="TestV" Text="{Binding Path=BindingContext.TestVal}" />
<!-- ^^^^ I want this Label to display the TestVal string in the ViewModel -->
<Label Text="{Binding Text}"
d:Text="{Binding .}"
LineBreakMode="NoWrap"
Style="{DynamicResource ListItemTextStyle}"
FontSize="16" />
<Label Text="{Binding Description}"
d:Text="Item descripton"
LineBreakMode="NoWrap"
Style="{DynamicResource ListItemDetailTextStyle}"
FontSize="13" />
<StackLayout.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Tapped="OnItemSelected"></TapGestureRecognizer>
</StackLayout.GestureRecognizers>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</RefreshView>
</StackLayout>
</ContentPage>
ItemsViewModel.cs
namespace TabTest.ViewModels
{
public class ItemsViewModel : BaseViewModel
{
public ObservableCollection<Item> Items { get; set; }
public Command LoadItemsCommand { get; set; }
private string testVal;
public string TestVal // I want the value of this variable in that Label
{
get
{
return testVal;
}
set
{
testVal = value;
}
}
public ItemsViewModel()
{
Title = "Browse";
TestVal = "Value123";
Items = new ObservableCollection<Item>();
LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());
MessagingCenter.Subscribe<NewItemPage, Item>(this, "AddItem", async (obj, item) =>
{
var newItem = item as Item;
Items.Add(newItem);
await DataStore.AddItemAsync(newItem);
});
}
async Task ExecuteLoadItemsCommand()
{
IsBusy = true;
try
{
Items.Clear();
var items = await DataStore.GetItemsAsync(true);
foreach (var item in items)
{
Items.Add(item);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}
}
}
I ended up using a dynamic resource in Xaml and used code behind to modify the resource when it needed to change.
Xaml:
<Label x:Name="TestV" Text="{DynamicResource TestValue}" />
Code Behind:
Application.Current.Resources["TestValue"] = NewValue;
App.xaml:
<x:String x:Key="TestValue">Value123</x:String>

How to set a binding to an element that was not instantiated in XAML code

I´m relative new to coding and I´m working on a little project. This is what I´m trying to do:
I defined a class "MyObject" with two properties:
namespace WpfApplication2
{
public class MyObject
{
public string Property1 { get; set; }
public int Property2 { get; set; }
public MyObject() : this("", 0)
{
}
public MyObject(string p1, int p2)
{
Property1 = p1;
Property2 = p2;
}
}
}
...then instantiated two objects of this class in code:
namespace WpfApplication2
{
public partial class MainWindow : Window
{
public List<MyObject> listOfMyObject { get; set; }
public MyObject myObj1 { get; set; }
public MyObject myObj2 { get; set; }
public MainWindow()
{
InitializeComponent();
listOfMyObject = new List<MyObject>();
myObj1 = new MyObject("Hello", 1);
myObj2 = new MyObject("Bye", 2);
listOfMyObject.Add(myObj1);
listOfMyObject.Add(myObj2);
}
}
}
Now I want to bind each property of the two MyObject objects to the Content Property of a Label object. So there should be four Label objects:
- Label1 should display the value of Property1 of myObj1
- Label2 should display the value of Property2 of myObj1
- Label3 should display the value of Property1 of myObj2
- Label4 should display the value of Property2 of myObj2
I tried it this way:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication2"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Name="mywin">
<Grid>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<StackPanel>
<Label Name="Label1" Content="{Binding ElementName=myObj1, Path=Property1}"/>
<Label Name="Label2" Content="{Binding ElementName=myObj1, Path=Property2}"/>
</StackPanel>
<StackPanel>
<Label Name="Label3" Content="{Binding ElementName=myObj2, Path=Property1}"/>
<Label Name="Label4" Content="{Binding ElementName=myObj2, Path=Property2}"/>
</StackPanel>
</StackPanel>
</Grid>
</Window>
... but it doesn´t work. Please help me to understand how to use the Binding correctly!
Greetings
// Even if I already figured out how to solve my problem, I would be pleased, // if someone could answer to the question at the end of this post!
Okay, now I figured out (with a little help from a friend), how to fix my problem:
I set the DataContext property of the MainWindow object, that contained the Label objects to itself by doing this:
mywin.DataContext = this;
So the code looks like this now:
public partial class MainWindow : Window
{
public List<MyObject> listOfMyObject { get; set; }
public MyObject myObj1 { get; set; }
public MyObject myObj2 { get; set; }
public MainWindow()
{
InitializeComponent();
listOfMyObject = new List<MyObject>();
myObj1 = new MyObject("Hello", 1);
myObj2 = new MyObject("Bye", 2);
listOfMyObject.Add(myObj1);
listOfMyObject.Add(myObj2);
// I added this code
mywin.DataContext = this;
}
}
And then I set the binding to the Content property of the four Label objects by doing this:
<Label Name="Label1" Content="{Binding Path=myObj1.Property1}" />
So my whole XAML code looks like this now:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication2"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Name="mywin">
<Grid>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<StackPanel>
<Label Name="Label1" Content="{Binding Path=myObj1.Property1}" />
<Label Name="Label2" Content="{Binding Path=myObj1.Property2}" />
</StackPanel>
<StackPanel>
<Label Name="Label3" Content="{Binding Path=myObj2.Property1}" />
<Label Name="Label4" Content="{Binding Path=myObj2.Property2}" />
</StackPanel>
</StackPanel>
</Grid>
</Window>
NEW Question:
Now I would like to understand, why it doesn´t work the way I tried in the first way...
<Label Name="Label1" Content="{Binding ElementName=myObj1, Path=Property1}"/>
... when this would work:
<Label Name="Label1" Content="{Binding ElementName=Label2, Path=Content}"/>
<Label Name="Label2" Content="Hello">
The XAML code, in which the Label objects are instantiated and the C# code, in which the MyObject objects are instantiated, are both partial classes that belong together. In addition to that the MyObject objects myObj1 and myObj2 are properties of this class. So I thought that the Label-Elements in the XAML code should "know" about the MyObject objects myObj1 and myObj2 and therefore be able to reference them as source elements in the ElementName property of the Binding object. Thinking this way, I thought I must only set the Path property of the Binding object to the Property which value the Label object should display.
Can you help me to understand, where my idea of Binding is wrong? Thank you!

What should I do to get the values of a listbox item in wpf c#?

I have a few images with some text, I need to get the image path with the relevant text in a listbox.
Browsing google I came across this sample class,
public class Img
{
public Img(string value, Image img) { Str = value; Image = img; }
public string Str { get; set; }
public Image Image { get; set; }
}
<ListBox x:Name="lstBox">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:Img}">
<StackPanel>
<TextBlock Margin="3" Text="{Binding Str}"/>
<ContentControl Margin="3" Content="{Binding Image}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
lstBox.Items.Add(new Img("Value", myImage));

binding a combobox to different DataContext

The combobox items are taken from one table, one field on which binding is made. After I saved in the database the selected item in another table, I want that the selected item to be the one which was saved. But the selected item is lost. So, my question is: can I bind the combobox to two DataContexts or maybe another solution ?.
To give an example to be more clear: the combobox items are predefined values taken from a datasource and the value selected must be saved and shown on the interface. So, from what I can see must be a binding to the predefined values and also a binding to the value saved to make a connection to the selected item.
Any suggestion?
Ioana, I don't seem to get what you're aiming at..
if you take this xaml:
<Window x:Class="WpfApplication4.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="300"
Width="300">
<StackPanel>
<TextBox Text="{Binding Path=SelectedText, Mode=TwoWay}"
Width="200"/>
<ComboBox Width="200"
VerticalAlignment="Center"
HorizontalAlignment="Center"
SelectedItem="{Binding Path=SelectedText, Mode=TwoWay}"
ItemsSource="{Binding Path=Texts, Mode=OneWay}">
</ComboBox>
</StackPanel>
</Window>
and this codebehind:
public partial class Window1 : INotifyPropertyChanged
{
public Window1()
{
InitializeComponent();
this.Texts = new List<string>(new[] {"foo","bar"});
this.DataContext = this;
}
private ObservableCollection<string> texts;
public ObservableCollection<string> Texts
{
get
{
return texts;
}
set
{
texts = value;
if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs("Texts"));
}
}
private string selectedText;
public string SelectedText
{
get
{
return selectedText;
}
set
{
selectedText = value;
if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs("SelectedText"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
You do have the Items and the selectedValue databound.
Notice the INotifyPropertyChanged.
Is this what you're trying to achieve ?

Dependency Properties and Data Context in Silverlight 3

I am working with Silverlight 3 beta, and am having an issue. I have a page that has a user control that I worte on it. The user control has a dependency property on it. If the user control does not define a data context (hence using the parent's data context), all works well. But if the user control has its own data context, the dependency property's OnPropertyChanged method never gets called.
Here is a sample:
My Main Page:
<UserControl x:Class="TestDepProp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:app="clr-namespace:TestDepProp"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="100">
<Grid x:Name="LayoutRoot" Background="White">
<Border BorderBrush="Blue" BorderThickness="3" CornerRadius="3">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical">
<TextBlock Text="Enter text here:" />
<TextBox x:Name="entryBlock" Text="{Binding Data, Mode=TwoWay}"/>
<Button Content="Go!" Click="Button_Click" />
<TextBlock Text="{Binding Data}" />
</StackPanel>
<Border BorderBrush="Blue" BorderThickness="3" CornerRadius="3" Margin="5">
<app:TestControl PropOnControl="{Binding Data}" />
</Border>
</StackPanel>
</Border>
</Grid>
</UserControl>
Main Page code:
using System.Windows;
using System.Windows.Controls;
namespace TestDepProp
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
MainPageData data = new MainPageData();
this.DataContext = data;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
int i = 1;
i++;
}
}
}
Main Page's data context:
using System.ComponentModel;
namespace TestDepProp
{
public class MainPageData:INotifyPropertyChanged
{
string _data;
public string Data
{
get
{
return _data;
}
set
{
_data = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Data"));
}
}
public MainPageData()
{
Data = "Initial Value";
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}
Control XAML:
<UserControl x:Class="TestDepProp.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:TestDepProp"
>
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Orientation="Vertical" Margin="10" >
<TextBlock Text="This should change:" />
<TextBlock x:Name="ControlValue" Text="Not Set" />
</StackPanel>
</Grid>
</UserControl>
Contol code:
using System.Windows;
using System.Windows.Controls;
namespace TestDepProp
{
public partial class TestControl : UserControl
{
public TestControl()
{
InitializeComponent();
// Comment out next line for DP to work
DataContext = new MyDataContext();
}
#region PropOnControl Dependency Property
public string PropOnControl
{
get { return (string)GetValue(PropOnControlProperty); }
set { SetValue(PropOnControlProperty, value); }
}
public static readonly DependencyProperty PropOnControlProperty =
DependencyProperty.Register("PropOnControl", typeof(string), typeof(TestControl), new PropertyMetadata(OnPropOnControlPropertyChanged));
private static void OnPropOnControlPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TestControl _TestControl = d as TestControl;
if (_TestControl != null)
{
_TestControl.ControlValue.Text = e.NewValue.ToString();
}
}
#endregion PropOnControl Dependency Property
}
}
Control's data context:
using System.ComponentModel;
namespace TestDepProp
{
public class MyDataContext : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}
To try it out, type something in the text box, and hit the Go button. Comment out the data context in the controls code to see that it starts to work.
Hope someone has an idea as to what is going on.
The user control's datacontext does not have a Data property.
Because it doesn't have a data property the databinding returns null which is already the default value so the property change never fires.

Resources