XML Parsing Error in Window Phone - silverlight

I'm creating a tweeter example in window phone and got NullReferenceException
I think it might be that the syntax is incorrect on the right side of the expression but couldn't tell what and why..
Anyone has an idea why this resulted in error?
.xaml.cs:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
string url = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=noradio";
WebClient twitter = new WebClient();
twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
twitter.DownloadStringAsync(new Uri(url));
}
void twitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
XElement xmlTweets = XElement.Parse(e.Result);
listBox1.ItemsSource = from tweet in xmlTweets.Descendants("Status")
select new TweeterItem
{
ImageSource = tweet.Element("user").Element("profile_image_url").Value,
Message = tweet.Element("text").Value,
UserName = tweet.Element("user").Element("screen_name").Value,
};
}
.xaml:
<ListBox Height="521" HorizontalAlignment="Left" Margin="0,131,0,0" Name="listBox1" VerticalAlignment="Top" Width="476">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding UserName}" Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

I usually do something like this, then I can check the values for null afterwards:
XmlReader xmlReader = XmlReader.Create(e.Result as Stream);
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
switch (xmlReader.Name)
{
case "profile_image_url":
ImageSource = xmlReader.ReadInnerXml();
break;
case "text":
Message = xmlReader.ReadInnerXml();
break;
case "screen_name":
UserName = xmlReader.ReadInnerXml();
break;
}
}
}

Related

How to set bind a text box to a class not in the data context class

I have this dock panel which I'm trying to set up bindings for.
The problem is that my DataContext for my XAML is set to the MainWindow class but my class that I want to bind to (autoCam) is separate from that class. I have an instance of autoCam being used in the MainWindow class, called "myCam", but I've gotten confused about how to get these bindings to work.
This is the code I'm using in my dock panel:
<DockPanel x:Name="BottomDock" Visibility="Collapsed" Grid.Column="2" Grid.Row="2" Grid.ColumnSpan="2" DockPanel.Dock="Bottom" Margin="0">
<Button x:Name="Rewind" Click="Rewind_Click" HorizontalAlignment="Left" Width="23" RenderTransformOrigin="0.5,0.5" Grid.Row="1"/>
<Button x:Name="Play" Content=">" Click="Play_Click" HorizontalAlignment="Left" Width="17" RenderTransformOrigin="0.5,0.5" Grid.Row="1"/>
<Button x:Name="Pause" Content="||" Click ="Pause_Click" HorizontalAlignment="Left" VerticalAlignment="Top" Width="16" Height="22" RenderTransformOrigin="0.5,0.5" Grid.Row="1"/>
<Button x:Name="FastForward" Content=">>" Click="FastForward_Click" HorizontalAlignment="Left" Width="23" RenderTransformOrigin="0.5,0.5" Grid.Row="1"/>
<TextBlock Background="Black" TextAlignment="Center" Foreground="AliceBlue" HorizontalAlignment="Left" Width="95" Text="Camera Position"/>
<TextBox Background="Black" TextAlignment="Center" Foreground="AliceBlue" HorizontalAlignment="Left" Width="40" Name="cpx" Text="{Binding Path=myCam.cameraPositionX, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Background="Black" TextAlignment="Center" Foreground="AliceBlue" HorizontalAlignment="Left" Width="40" Name="cpy" Text="{Binding Path=myCam.cameraPositionY, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Background="Black" TextAlignment="Center" Foreground="AliceBlue" HorizontalAlignment="Left" Width="40" Name="cpz" Text="{Binding Path=myCam.cameraPositionZ, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Background="Black" TextAlignment="Center" Foreground="AliceBlue" HorizontalAlignment="Left" Width="95" Text="Look Direction"/>
<TextBox Background="Black" TextAlignment="Center" Foreground="AliceBlue" HorizontalAlignment="Left" Width="40" Name="ldx" Text="{Binding Path=myCam.lookDirectionX, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Background="Black" TextAlignment="Center" Foreground="AliceBlue" HorizontalAlignment="Left" Width="40" Name="ldy" Text="{Binding Path=myCam.lookDirectionY, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Background="Black" TextAlignment="Center" Foreground="AliceBlue" HorizontalAlignment="Left" Width="40" Name="ldz" Text="{Binding Path=myCam.lookDirectionZ, UpdateSourceTrigger=PropertyChanged}"/>
</DockPanel>
At first I thought I could just write DataContext=autoCam as a property of the dock panel itself, or for each individual textbox and then just say {binding cameraPositionX} or something, but that didn't do anything.
Then i thought I could just say {Binding myCam.cameraPositionX} since myCam is a member of the MainWindow class. But that didn't work either.
In a futile attempt, I tried to sort of combine both of my guesses and add DataContext=autoCam to properties of all of the text boxes but I never thought that would actually work.
I also tried to write the following after the datacontext=this; line in the mainwindow constructor. I tried this in case the problem was that the xaml would set the datacontext properly as i wanted it, but then the datacontext for the entire ui would be reapplied to the mainwindow when the constructor was run.
public MainWindow()
{
InitializeComponent();
Interval = new TimeSpan(0, 0, 0, 0, 10);
Rewind.Content = "<<";
runType = 2;
timerRate(runType);
Loaded += new RoutedEventHandler(MainWindow_Loaded);
DataContext = this;
cpx.DataContext = myCam;
cpy.DataContext = myCam;
cpx.DataContext = myCam;
ldx.DataContext = myCam;
ldy.DataContext = myCam;
ldz.DataContext = myCam;
//view1.IsHeadLightEnabled = true;
}
I thought that maybe I could put this in the Window.Resources XAML:
<Window.Resources>
<ObjectDataProvider x:Key="Camera" ObjectType="{x:Type local:autoCam}" MethodName="getCamDetails"/>
</Window.Resources>
but i wrote my method getCamDetails in my autoCam class as follows, and it's giving me a null reference exception every time i try to set CamDetails[0] to cameraPositionX.
public class autoCam : INotifyPropertyChanged
{
MainWindow mW;
public static double[] CamDetails;
public static double[] getCamDetails()
{
return CamDetails;
}
public Point3D cameraPosition
{
get { return mC.Position; }
set
{
mC.Position = value;
cameraPositionX = Convert.ToDouble(cameraPosition.X);
cameraPositionY = Convert.ToDouble(cameraPosition.Y);
cameraPositionZ = Convert.ToDouble(cameraPosition.Z);
lookDirection = mC.LookDirection;
lookDirectionX = Convert.ToDouble(lookDirection.X);
lookDirectionY = Convert.ToDouble(lookDirection.Y);
lookDirectionZ = Convert.ToDouble(lookDirection.Z);
onPropertyChanged("cameraPosition");
}
}
public double cameraPositionX
{
get { return Convert.ToDouble(cameraPosition.X); }
set { onPropertyChanged("cameraPositionX"); CamDetails[0] = cameraPositionX; }
}
public double cameraPositionY
{
get { return Convert.ToDouble(cameraPosition.Y); }
set { onPropertyChanged("cameraPositionY"); CamDetails[1] = cameraPositionY; }
}
public double cameraPositionZ
{
get { return Convert.ToDouble(cameraPosition.Z); }
set { onPropertyChanged("cameraPositionZ"); CamDetails[2] = cameraPositionZ; }
}
public Vector3D lookDirection
{
get { return mC.LookDirection; }
set {
mC.LookDirection = value;
lookDirectionX = Convert.ToDouble(lookDirection.X);
lookDirectionY = Convert.ToDouble(lookDirection.Y);
lookDirectionZ = Convert.ToDouble(lookDirection.Z);
onPropertyChanged("lookDirection");
}
}
public double lookDirectionX
{
get { return Convert.ToDouble(lookDirection.X);}
set { onPropertyChanged("lookDirectionX"); CamDetails[3] = lookDirectionX; }
}
public double lookDirectionY
{
get { return Convert.ToDouble(lookDirection.Y); }
set { onPropertyChanged("lookDirectionY"); CamDetails[4] = lookDirectionY; }
}
public double lookDirectionZ
{
get { return Convert.ToDouble(lookDirection.Z); }
set { onPropertyChanged("lookDirectionZ"); CamDetails[5] = lookDirectionZ; }
I would really appreciate a solution, but a break down of why these aren't working for me is essentially going to help me a lot more in the long run.
Thank you for your time and help everyone.
It would have been better to share the MainWindow class too but it sounds like putting a property in your MainWindow class to expose the myCam instance and binding directly to that property should work.
public partial class MainWindow : Window
{
private AutoCam autoCam;
public AutoCam AutoCam
{
get { return autoCam; }
set { autoCam = value; }
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
this.autoCam = new AutoCam();
}
}
public class AutoCam
{
private string someText;
public string SomeText
{
get { return someText; }
set { someText = value; }
}
public AutoCam()
{
this.SomeText = "Some Text";
}
}
And the binding will be like this.
<Label Content="{Binding AutoCam.SomeText}">

Event Aggregator in Prism usage giving exception

I have to communicate between 2 view models so I am using Event aggregator but I observed the method is calling 2 times when a property is updated and for the first it is working as expected but second time all the elements are null and throwing null reference exception.
Why it is happening I am not triggering it second time.
MainViewModel
private XMLNode NodeSelected;
public XMLNode NodeSelected
{
get { return NodeSelected; }
set
{
nodeSelected = value;
iEventAggregator.GetEvent<AddNewObjectEvent>().Publish(this.NodeSelected);
}
}
UsercontrolViewModel
public UserControlViewModel(IEventAggregator iEventAggregator)
{
this.iEventAggregator = iEventAggregator;
this.iEventAggregator.GetEvent<AddNewGuiSyncObjectEvent>()
.Subscribe(AddXMLNode);
}
AddXMLNODE method related code
private void AddXMLNODE (XMLNode SelectedNode)
{
if (this.CriteriaItem == null) return;
SyncObject currentObj = new SyncObject(SelectedNode);
if (!IsSyncItemNameUnique(currentObj))
{
currentObj.Name = GetUniqueName(currentObj);
}
this.CriteriaItem.SyncObjects.Add(currentObj);
this.SelectedSyncObject = this.CriteriaItem .SyncObjects.LastOrDefault();
}
Here first time "CriteriaItem" is coming correct and newnode is added to collection but again same method is hitting and CriteriaItem is NULL If I remove that null check we are getting exception.
What is the mistake here I am not getting.
The complete code
UserControl ViewModel
namespace Hexagon.SmartUITest.GUISynchronization.ViewModel
{
public class IndividualSyncViewModel : ViewModelBase
{
#region properties
private GUISyncObject selectedSyncObject;
public GUISyncObject SelectedSyncObject
{
get { return selectedSyncObject; }
set
{
selectedSyncObject = value;
this.OnPropertyChanged(() => this.SelectedSyncObject);
iEventAggregator.GetEvent<SelectedSyncObjectEvent>().Publish(this.SelectedSyncObject);
}
}
private SyncCriteriaItem _CriteriaItem;
public SyncCriteriaItem CriteriaItem
{
get { return CriteriaItem; }
set
{
CriteriaItem = value;
OnPropertyChanged(() => this.CriteriaItem);
}
}
private IEventAggregator iEventAggregator;
#endregion
#region constructor
public IndividualSyncViewModel(IEventAggregator iEventAggregator)
{
this.iEventAggregator = iEventAggregator;
this.iEventAggregator.GetEvent<AddNewGuiSyncObjectEvent>()
.Subscribe(AddGUISyncItem);
}
#endregion
private ICommand deleteSyncObjectClick;
public ICommand DeleteSyncObjectClick
{
get
{
if (deleteSyncObjectClick == null) deleteSyncObjectClick = new RelayCommand(DeleteSync);
return deleteSyncObjectClick;
}
set
{
deleteSyncObjectClick = value;
}
}
private void DeleteSync()
{
this.CriteriaItem.SyncObjects.Remove(selectedSyncObject);
selectedSyncObject = this.CriteriaItem.SyncObjects.LastOrDefault();
}
private bool IsItemNameUnique(GUISyncObject SyncObject)
{
if (this.CriteriaItem != null && this.CriteriaItem.SyncObjects.Count == 0)
return true;
foreach (GUISyncObject item in this.CriteriaItem.SyncObjects.ToList())
{
if (item.Name.Equals(SyncObject.Name) && !item.CommandNodeName.Equals(SyncObject.CommandNodeName))
return false;
}
return true;
}
private string GetUniqueName(GUISyncObject syncItem)
{
List<string> itemsNames = this.CriteriaItem.SyncObjects.Select(item => item.Name).ToList();
return CommonNamingRules.GetUniqueName(itemsNames, syncItem.Name);
}
private void AddGUISyncItem(ControlNode SelectedNode)
{
if (this.CriteriaItem == null) return;
GUISyncObject currentObj = new GUISyncObject(SelectedNode);
if (!IsSyncItemNameUnique(currentObj))
{
currentObj.Name = GetUniqueName(currentObj);
}
this.CriteriaItem.SyncObjects.Add(currentObj);
this.SelectedSyncObject = this.CriteriaItem.SyncObjects.LastOrDefault();
}
}
}
UserControl xaml.cs
public partial class IndividualSync : UserControl
{
private IndividualSyncViewModel _vm;
public IndividualSync()
{
InitializeComponent();
_vm = new IndividualSyncViewModel(Event.EventInstance.EventAggregator);
rootGrid.DataContext = _vm;
}
#region properties
public SyncCriteriaItem SyncCriteriaItem
{
get { return (SyncCriteriaItem)GetValue(SyncCriteriaItemProperty); }
set { SetValue(SyncCriteriaItemProperty, value); }
}
public static readonly DependencyProperty SyncCriteriaItemProperty = DependencyProperty.Register("SyncCriteriaItem", typeof(SyncCriteriaItem), typeof(IndividualSync), new PropertyMetadata(null, OnCriteriaItemSet));
public GUISyncObject SelectedSYNC
{
get { return (GUISyncObject)GetValue(SelectedSYNCDependencyProperty); }
set { SetValue(SelectedSYNCDependencyProperty, value); }
}
public static readonly DependencyProperty SelectedSYNCDependencyProperty = DependencyProperty.Register("SelectedSYNC", typeof(GUISyncObject), typeof(IndividualSync), new PropertyMetadata(null, OnGUISyncItemSelect));
private static void OnCriteriaItemSet(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((IndividualSync)d)._vm.CriteriaItem = e.NewValue as SyncCriteriaItem;
}
private static void OnSyncItemSelect(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((IndividualSync)d)._vm.SelectedSyncObject = e.NewValue as GUISyncObject;
}
#endregion
}
Iam creating two dependency properties on the usercontrol which will be set from parent usercontrol.
Parent usercontrol Xaml
<UserControl.Resources>
<Converters:IndexToTabNameConverter x:Key="TabIndexConverter"/>
<DataTemplate x:Key="SyncTabItemTemplate" >
<StackPanel VerticalAlignment="Center"
Orientation="Horizontal">
<TextBlock Text="{Binding Converter={StaticResource TabIndexConverter},
RelativeSource={RelativeSource AncestorType={x:Type telerik:RadTabItem}}}"/>
<Button Margin="10,0,0,0"
Style="{StaticResource CloseButton}"
ToolTipService.ToolTip="Save and Close">
<Button.Content>
<Path Data="M0,0 L6,6 M6, 0 L0,6"
SnapsToDevicePixels="True"
Stroke="Black"
StrokeThickness="1" />
</Button.Content>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<uxt:EventToCommand CommandParameter="{Binding}" Command="{Binding Path=DataContext.RemoveSyncCriteriaCommand,ElementName=rootGrid}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="EmptyTemplate">
<TextBlock FontWeight="Bold" FontFamily="Comic Sans" FontStyle="Italic" Text="{Binding}" />
</DataTemplate>
<DataTemplate x:Key="HeaderTemplate">
<Label FontWeight="Bold" HorizontalContentAlignment="Center" Content="{Binding}" />
</DataTemplate>
<DataTemplate x:Key="SyncCriteriaTemplate">
<local:IndividualSync SyncCriteriaItem="{Binding}" SelectedGUISYNC="{Binding Path=DataContext.SelectedGUISYNCOBJECT}"/>
</DataTemplate>
<DataTemplate x:Key="newTabButtonHeaderTemplate">
<telerik:RadButton Style="{DynamicResource IconButtonStyle}" Width="20" Height="20" Command="{Binding Path=DataContext.NewCommand,ElementName=rootGrid}" ToolTip="Click to add new item">
<uxt:UxtXamlImage Template="{DynamicResource Com_Add}" />
</telerik:RadButton>
</DataTemplate>
<DataTemplate x:Key="itemContentTemplate">
<Grid/>
</DataTemplate>
<Selectors:TabItemTemplateSelector x:Key="headerTemplateSelector"
NewButtonTemplate="{StaticResource newTabButtonHeaderTemplate}"
ItemTemplate="{StaticResource SyncTabItemTemplate}"/>
<Selectors:TabItemTemplateSelector x:Key="contentTemplateSelector"
NewButtonTemplate="{StaticResource itemContentTemplate}"
ItemTemplate="{StaticResource SyncCriteriaTemplate}"/>
<Selectors:SyncTemplateSelector x:Key="syncTemplates">
<Selectors:SyncTemplateSelector.ProcessSyncTemplate>
<DataTemplate>
<telerik:Label Content="{Binding ProcessSync,StringFormat={}{0}}" BorderThickness="1" HorizontalContentAlignment="Left" FontStyle="Oblique" Width="{Binding Width,RelativeSource={RelativeSource AncestorType=telerik:RadListBox}}"/>
</DataTemplate>
</Selectors:SyncTemplateSelector.ProcessSyncTemplate>
<Selectors:SyncTemplateSelector.GUISyncTemplate>
<DataTemplate>
<Expander Header="GUISYNC" HeaderTemplate="{StaticResource HeaderTemplate}" Width="{Binding Width,RelativeSource={RelativeSource AncestorType=telerik:RadListBox}}" IsExpanded="{Binding Mode=TwoWay, Path=IsSelected, RelativeSource={RelativeSource AncestorType=telerik:RadListBoxItem, Mode=FindAncestor}}">
<telerik:RadTabControl ItemsSource="{Binding SyncCriteriaItem}" OverflowMode="Scroll" DropDownDisplayMode="Visible" SelectedItem="{Binding SelectedSyncCriteria, Mode=TwoWay}" SelectedIndex="0"
ItemTemplateSelector="{StaticResource headerTemplateSelector}"
ContentTemplateSelector="{StaticResource contentTemplateSelector}">
</telerik:RadTabControl>
</Expander>
</DataTemplate>
</Selectors:SyncTemplateSelector.GUISyncTemplate>
</Selectors:SyncTemplateSelector>
</UserControl.Resources>
<Grid Name="rootGrid">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<telerik:RadListBox Margin="20,5,20,0" Grid.Row="0" Grid.Column="0" Name="synclist" ItemsSource="{Binding CurrentSyncObjectCollection.SyncObjects}" ItemTemplateSelector="{StaticResource syncTemplates}" SelectedItem="{Binding SelectedSyncObject,Mode=TwoWay}" >
</telerik:RadListBox>
<telerik:RadComboBox Grid.Row="1" Grid.Column="0" Name="SyncOption" EmptyText="Select a sync type to be added " Margin="0,8,0,5" EmptySelectionBoxTemplate="{StaticResource EmptyTemplate}" ItemsSource="{Binding SyncTypes}" Width="{Binding ActualWidth, ElementName=synclist}" HorizontalContentAlignment="Center" Height="25" SelectedIndex="{Binding SelectedSyncIndex,Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<uxt:EventToCommand Command="{Binding AddSelectedSyncClick}" CommandParameter="{Binding Path=SelectedValue,ElementName=SyncOption}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</telerik:RadComboBox>
<telerik:RadButton Style="{DynamicResource IconButtonStyle}" Grid.Column="1" Grid.Row="0" Width="20" Height="20" VerticalAlignment="Top" IsEnabled="{Binding Path=SelectedSyncObject,Converter={uxt:ObjectToBoolConverter}}" ToolTip="Click to delete selected Sync"
Command="{Binding DeleteSyncObjectClick}">
<uxt:UxtXamlImage Template="{DynamicResource Com_Delete}" />
</telerik:RadButton>
</Grid>
I hope this will help. I have debugged the code and I observed even two Items are binded for CriteriaItems Breakpoint hitting for dependency property criteria item 3 times and one time null is coming.
Even when I change Tab selection Dependency Property setting code is hitting 2 times instead of one time.first time null is setting for CriteriaItem and second time respective item is coming.

Binding all texts in TextBox from a html file - HtmlAgility

I have to make this app to show all texts from a html file, each text in his TextBox. so i did this ti'll now and i don't know how to continue:
.xaml.cs
public MainWindow()
{
InitializeComponent();
}
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
private void Button_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "HTM | *.htm";
if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
doc.Load(open.OpenFile());
var listItems = doc.DocumentNode.SelectSingleNode("//ul").SelectNodes("li");
var src = new List<string>();
foreach (var li in listItems)
{
src.AddRange(li.Descendants("p").Select(x => x.InnerText));
}
myListBox.ItemsSource = src;
}
.xaml
<Grid>
<Button Content="Open" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
<ListBox Name="myListBox" HorizontalAlignment="Left" Height="249" Margin="10,48,0,0" VerticalAlignment="Top" Width="497">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Height="23" TextWrapping="Wrap" Width="400" Text="{Binding Description}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Oh I think I see your problem... you're trying to data bind to a property named Description in your XAML. Would you like to show me where that property was declared, because I can't see one. Furthermore, your ListBox.ItemsSource is set to a List<string>, so there can't be any Description property to bind to. Instead, try this:
<TextBox Height="23" TextWrapping="Wrap" Width="400" Text="{Binding}" />

Databinding issue in windows phone

Hi I am trying to study the data binding property in windows phone. I googled and got some blogs. As learned from those blogs I binded values in a ListBox. Now the listbox showng many products with name, amount , date, image properties. But now I am trying to do this, if click on any product in the list I want to navigate to other page and display the product details there. But in that page the databinding is not working. Just those textblocks shows nothing. I included my code below. Please help me to find the problem in my code.
Transaction.cs
public class Transaction
{
public String Name { get; set; }
public String Date { get; set; }
public int Amount { get; set; }
public String Type { get; set; }
public Transaction(String name, String date, int amount,String type)
{
this.Name = name;
this.Date = date;
this.Amount = amount;
this.Type = type;
}
}
public class ShowItem
{
public String SelectedItemName { get; set; }
public String SelectedItemImage { get; set; }
public String SelectedItemDate { get; set; }
public String SelectedItemAmount { get; set; }
public ShowItem(String name, String date, String amount, String image)
{
this.SelectedItemName = name;
this.SelectedItemDate = date;
this.SelectedItemAmount = amount;
this.SelectedItemImage = image;
}
}
MainPage.xaml
<Grid Height="530" Grid.Row="1" VerticalAlignment="Top" Margin="0,30,0,0">
<ListBox Margin="0,0,0,0" Name="TransactionList">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Width="460" Height="150" BorderThickness="0" Click="user_click" Name="rowButton" Background="{Binding Color}" >
<Button.Content>
<StackPanel Orientation="Horizontal" Height="auto" Width="400">
<Image Width="80" Height="80" Source="{Binding Type}"></Image>
<StackPanel Orientation="Vertical" Height="150" Margin="20,0,0,0">
<StackPanel Orientation="Horizontal" Height="40">
<TextBlock Width="100" FontSize="22" Text="Name :" Height="40" ></TextBlock>
<TextBlock Width="auto" FontSize="22" Text="{Binding Name}" Height="40" ></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="40">
<TextBlock Width="100" FontSize="22" Text="Date :" Height="40" ></TextBlock>
<TextBlock Width="100" FontSize="22" Text="{Binding Date}" Height="40" ></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="40">
<TextBlock Width="100" FontSize="22" Text="Amount :" Height="40" ></TextBlock>
<TextBlock Width="auto" FontSize="22" Text="{Binding Amount}" Height="40" ></TextBlock>
<TextBlock Width="auto" FontSize="22" Text=" $" Height="40" ></TextBlock>
</StackPanel>
</StackPanel>
</StackPanel>
</Button.Content>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
MainPage.xaml.cs
public partial class MainPage : PhoneApplicationPage
{
string[] _dates = { "19/9/1984", "25/8/1952", "27/5/1992", "4/8/1975", "10/3/2000", "22/1/2002", "23/5/2012", "25/9/1963", "13/7/1999", "15/4/1936" };
string[] _imageList = { "69290979.png", "acrobat-reader-cs-4.png","azureus-1.png","ClothDolls_lnx-Icons-Colored_Blue_Doll_256x256.png-256x256.png","database-27.png",
"documents-folder-2.png", "Front_Row_Icon.png","gear-8.png","info-chat.png","itunes-6.png","nero-smart-start-1.png",
"network-2.png","picasa.png","quicktime-7-red.png","twitter-bird.png","wlm-1.png" };
string[] _items = { "Television", "Radio", "Fridge", "Fan", "Light", "Cup", "Plate", "Dress", "Laptop", "Mobile" };
int[] _prices = { 10, 15, 20, 25, 30, 5, 8, 15, 10, 20 };
List<Transaction> transactionList;
// Constructor
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
int count = 50;
String DefaultName = "";
String DefaultDate = "";
int DefaultAmount = 0;
String DefaultImage = "";
transactionList = new List<Transaction>();
Random random = new Random();
for (int i = 0; i < _items.Length; i++)
{
DefaultName = _items[i];
DefaultDate = _dates[i];
DefaultAmount = _prices[i];
DefaultImage = "Images/" + _imageList[random.Next(0, _imageList.Length)];
transactionList.Add(new Transaction(DefaultName, DefaultDate, DefaultAmount, DefaultImage));
}
TransactionList.ItemsSource = transactionList;
}
private void user_click(object sender, RoutedEventArgs e)
{
var myData = ((Button)sender).DataContext as Transaction;
NavigationService.Navigate(new Uri("/DisplayProduct.xaml?Name=" + myData.Name +"&Date=" + myData.Date + "&Amount=" + myData.Amount + "&Type=" + myData.Type, UriKind.Relative));
}
}
DisplayProduct.xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel Orientation="Vertical">
<StackPanel HorizontalAlignment="Center">
<Image Width="auto" Height="auto" Name="itemImage" Source="{Binding SelectedItemImage}"></Image>
</StackPanel>
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" Width="350" HorizontalAlignment="Left">
<StackPanel Orientation="Horizontal" Margin="0,20,0,0">
<TextBlock Text="Name : " Width="150" Height="70" FontSize="35" Foreground="DarkSalmon"></TextBlock>
<TextBlock Name="itemName" Text="{Binding SelectedItemName}" Width="auto" Height="70" FontSize="35"></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,20,0,0">
<TextBlock Text="Amount : " Width="150" Height="70" FontSize="35" Foreground="DarkSalmon"></TextBlock>
<TextBlock Name="itemPrice" Text="{Binding SelectedItemAmount}" Width="auto" Height="70" FontSize="35"></TextBlock>
<TextBlock Name="currency" Text="$" Width="auto" Height="70" FontSize="35"></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,20,0,0">
<TextBlock Text="Date : " Width="150" Height="70" FontSize="35" Foreground="DarkSalmon"></TextBlock>
<TextBlock Name="itemDate" Text="{Binding SelectedItemDate}" Width="auto" Height="70" FontSize="35"></TextBlock>
</StackPanel>
</StackPanel>
</StackPanel>
</StackPanel>
</Grid>
DisplayProduct.xaml.cs
public partial class DisplayProduct : PhoneApplicationPage
{
public DisplayProduct()
{
InitializeComponent();
Loaded += new RoutedEventHandler(DisplayProduct_Loaded);
}
void DisplayProduct_Loaded(object sender, RoutedEventArgs e)
{
string name = NavigationContext.QueryString["Name"];
string date = NavigationContext.QueryString["Date"];
string amount = NavigationContext.QueryString["Amount"];
string type = NavigationContext.QueryString["Type"];
ShowItem showItemClass = new ShowItem(name, date, amount, type);
}
}
void DisplayProduct_Loaded(object sender, RoutedEventArgs e)
{
string name = NavigationContext.QueryString["Name"];
string date = NavigationContext.QueryString["Date"];
string amount = NavigationContext.QueryString["Amount"];
string type = NavigationContext.QueryString["Type"];
ShowItem showItemClass = new ShowItem(name, date, amount, type);
DataContext = showItemClass;
}
You forgot to set the DataContext of the page. It doesn't know where should it get data to display.

ListBox binding with ViewModel in WPF

I am new to the WPF and trying to build a sample application using the MVVM framework. My application has a xaml file which has some textboxes for inputing customer info, combo box for display of states and a save button. All the databinding is done through ViewModel(CustomerViewMode) which has a reference to the Model(Customer), containing the required fields and their
Getter, setters. The viewModel has a CustomerList property.
On clicking the save button, I want to display the FirstName and LastName properties of Customer in a ListBox. This is where the problem is. I debugged the code,
(Click event of button in the code behind), I can see that the CustomerList has the first Customer object with all its details, but its not getting displayed in the listbox.
My code is:
Customer(Model);
enter code here
namespace SampleMVVM.Models
{
class Customer : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private String _firstName;
private String _lastName;
private Address _customerAddress;
public String FirstName
{
get { return _firstName; }
set
{
if (value != _firstName)
{
_firstName = value;
RaisePropertyChanged("FirstName");
}
}
}
public String LastName
{
get { return _lastName; }
set
{
if (value != _lastName)
{
_lastName = value;
RaisePropertyChanged("LastName");
}
}
}
public Address CustomerAddress
{
get { return _customerAddress; }
set
{
if (value != _customerAddress)
{
_customerAddress = value;
RaisePropertyChanged("CustomerAddress");
}
}
}
private void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Address(Model)
namespace SampleMVVM.Models
{
class Address : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _addressLine1;
private string _addressLine2;
private string _city;
//private string _selectedState;
private string _postalCode;
private string _country;
public String AddressLine1
{
get { return _addressLine1; }
set
{
if (value != _addressLine1)
{
_addressLine1 = value;
RaisePropertyChanged(AddressLine1);
}
}
}
public String AddressLine2
{
get { return _addressLine2; }
set
{
if (value != _addressLine2)
{
_addressLine2 = value;
RaisePropertyChanged(AddressLine2);
}
}
}
public String City
{
get { return _city; }
set
{
if (value != _city)
{
_city = value;
RaisePropertyChanged(City);
}
}
}
public String PostalCode
{
get { return _postalCode; }
set
{
if (value != _postalCode)
{
_postalCode = value;
RaisePropertyChanged(PostalCode);
}
}
}
public String Country
{
get { return _country; }
set
{
if (value != _country)
{
_country = value;
RaisePropertyChanged(Country);
}
}
}
private void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
CustomerViewModel:
namespace SampleMVVM.ViewModels
{
class CustomerViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Customer _customer;
RelayCommand _saveCommand;
private List<String> _stateList = new List<string>();
private string _selectedState;
private ObservableCollection<Customer> _customerList = new ObservableCollection<Customer>();
//public CustomerViewModel(ObservableCollection<Customer> customers)
//{
// _customers = new ListCollectionView(customers);
//}
public Customer CustomerModel
{
get { return _customer; }
set
{
if (value != _customer)
{
_customer = value;
RaisePropertyChanged("CustomerModel");
}
}
}
public List<String> StateList
{
get
{
return _stateList;
}
set { _stateList = value; }
}
public ObservableCollection<Customer> CustomerList
{
get
{
return _customerList;
}
set
{
if (value != _customerList)
{
_customerList = value;
RaisePropertyChanged("CustomerList");
}
}
}
public CustomerViewModel()
{
CustomerModel = new Customer
{
FirstName = "Fred",
LastName = "Anders",
CustomerAddress = new Address
{
AddressLine1 = "Northeastern University",
AddressLine2 = "360, Huntington Avenue",
City = "Boston",
PostalCode = "02115",
Country = "US",
}
};
StateList = new List<String>
{
"Alaska", "Arizona", "California", "Connecticut", "Massachusetts", "New Jersey", "Pennsylvania", "Texas"
};
SelectedState = StateList.FirstOrDefault();
}
public String SelectedState
{
get { return _selectedState; }
set
{
if (value != _selectedState)
{
_selectedState = value;
RaisePropertyChanged(SelectedState);
}
}
}
private void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
CustomerInfo.xaml(view)
<UserControl x:Class="SampleMVVM.Views.CustomerInfo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ViewModels="clr-namespace:SampleMVVM.ViewModels"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.DataContext>
<ViewModels:CustomerViewModel />
</UserControl.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<!--Starting label-->
<TextBlock FontSize="18" FontFamily="Comic Sans MS" FontWeight="ExtraBlack"
Foreground="Navy"
Grid.Row="0" HorizontalAlignment="Center">
<TextBlock.Text>
Customer Information:
</TextBlock.Text>
</TextBlock>
<TextBlock Text="First name: " Grid.RowSpan="2" HorizontalAlignment="Left" VerticalAlignment="Top"
Grid.Row="1" Width="80px" Height="50px" Margin="40,5,0,0"/>
<TextBox Text="{Binding CustomerModel.FirstName}" Grid.RowSpan="2" HorizontalAlignment="Left"
VerticalAlignment="Top"
Grid.Row="1" Grid.Column="1" Width="80px" Height="20px" Margin="20,5,0,0" Name="fname"/>
<TextBlock Text="Last Name: " Grid.RowSpan="2" HorizontalAlignment="Left" VerticalAlignment="Top"
Grid.Row="2" Width="80px" Height="50px" Margin="40,5,0,0"/>
<TextBox Text="{Binding CustomerModel.LastName}" Grid.RowSpan="2" HorizontalAlignment="Left"
VerticalAlignment="Top"
Grid.Row="2" Grid.Column="1" Width="80px" Height="20px" Margin="20,5,0,0" Name="lname"/>
<TextBlock Text="Address: " Grid.RowSpan="2" HorizontalAlignment="Left" VerticalAlignment="Top"
Grid.Row="3" Width="80px" Height="50px" Margin="40,5,0,0"/>
<TextBox Text="{Binding CustomerModel.CustomerAddress.AddressLine1}" Grid.RowSpan="2" HorizontalAlignment="Left"
VerticalAlignment="Top"
Grid.Row="3" Grid.Column="1" Width="160px" Height="20px" Margin="20,5,0,0"/>
<TextBox Text="{Binding CustomerModel.CustomerAddress.AddressLine2}" Grid.RowSpan="2" HorizontalAlignment="Left"
VerticalAlignment="Top"
Grid.Row="4" Grid.Column="1" Width="160px" Height="30px" Margin="20,5,0,0"/>
<TextBlock Text="City: " Grid.RowSpan="2" HorizontalAlignment="Left" VerticalAlignment="Top"
Grid.Row="5" Width="80px" Height="20px" Margin="40,5,0,0"/>
<TextBox Text="{Binding CustomerModel.CustomerAddress.City}" Grid.RowSpan="2" HorizontalAlignment="Left"
VerticalAlignment="Top"
Grid.Row="5" Grid.Column="1" Width="80px" Height="20px" Margin="20,5,0,0"/>
<TextBlock Text="State: " Grid.RowSpan="2" HorizontalAlignment="Left" VerticalAlignment="Top"
Grid.Row="6" Width="80px" Height="20px" Margin="40,5,0,0"/>
<ComboBox Grid.RowSpan="2" HorizontalAlignment="Left" Name="listOfSates"
VerticalAlignment="Top"
Grid.Row="6" Grid.Column="1" Width="80px" Height="20px" Margin="20,5,0,0"
ItemsSource="{Binding Path=StateList}"
SelectedItem="{Binding Path=SelectedState}"
SelectionChanged="ComboBox_SelectionChanged"
>
</ComboBox>
<TextBlock Text="PostalCode: " Grid.RowSpan="2" HorizontalAlignment="Left" VerticalAlignment="Top"
Grid.Row="7" Width="80px" Height="20px" Margin="40,5,0,0"/>
<TextBox Text="{Binding CustomerModel.CustomerAddress.PostalCode}" Grid.RowSpan="2" HorizontalAlignment="Left"
VerticalAlignment="Top"
Grid.Row="7" Grid.Column="1" Width="80px" Height="20px" Margin="20,5,0,0"/>
<TextBlock Text="Country: " Grid.RowSpan="2" HorizontalAlignment="Left" VerticalAlignment="Top"
Grid.Row="8" Width="80px" Height="20px" Margin="40,5,0,0"/>
<TextBox Text="{Binding CustomerModel.CustomerAddress.Country}" Grid.RowSpan="2" HorizontalAlignment="Left"
VerticalAlignment="Top"
Grid.Row="8" Grid.Column="1" Width="80px" Height="20px" Margin="20,5,0,0"/>
<Button Content="Save" Grid.RowSpan="2" HorizontalAlignment="Left" VerticalAlignment="Top"
Grid.Row="9" Width="50px" Height="20px" Name="savebtn" Margin="40,5,0,0"
Click="savebtn_Click"/>
<ListBox Name="cList" ItemsSource="{Binding Path=CustomerList}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Grid.Row="1" Grid.Column="2" Grid.RowSpan="2" Width="200px" Height="300px" Margin="200,5,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding CustomerModel.FirstName}"
FontWeight="Bold" Foreground="Navy"/>
<TextBlock Text=", " />
<TextBlock Text="{Binding CustomerModel.LastName}"
FontWeight="Bold" Foreground="Navy"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
CustomerInfo(Code behind class)
namespace SampleMVVM.Views
{
/// <summary>
/// Interaction logic for CustomerInfo.xaml
/// </summary>
public partial class CustomerInfo : UserControl
{
public CustomerInfo()
{
InitializeComponent();
//checkvalue();
}
private void savebtn_Click(object sender, RoutedEventArgs e)
{
////Customer c = new Customer();
////c.FirstName = fname.Text;
////c.LastName = lname.Text;
//CustomerViewModel cvm = new CustomerViewModel();
//cvm.CustomerModel.FirstName = fname.Text;
//cvm.CustomerModel.LastName = lname.Text;
//List<CustomerViewModel> customerList = new List<CustomerViewModel>();
//customerList.Add(cvm);
var viewModel = DataContext as CustomerViewModel;
if (viewModel != null)
{
//viewModel.ShowCustomerInfo();
String strfname = viewModel.CustomerModel.FirstName;
String strname = viewModel.CustomerModel.LastName;
viewModel.CustomerList.Add(viewModel.CustomerModel);
String str1 = viewModel.CustomerList.FirstOrDefault().FirstName;
int i = viewModel.CustomerList.Count();
//cList.ItemsSource = viewModel.CustomerList;
}
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
CustomerViewModel cvm = new CustomerViewModel();
cvm.SelectedState = listOfSates.SelectedItem.ToString();
}
}
}
I just cant understand where am I going wrong...Someone please help
And for the correct binding in ListBox.ItemTemplate:
<TextBlock Text="{Binding FirstName}"
FontWeight="Bold" Foreground="Navy"/>
<TextBlock Text="{Binding LastName}"
FontWeight="Bold" Foreground="Navy"/>
The DataContext of ListBoxItem is a Customer already.
You only create a new instance of a CustomerModel object once in your code (in the Customer View Model constructor). So you are constantly updating the same customer object rather than creating a new one.
At the end of your click handler you should do a
viewModel.CustomerModel = new Customer();
HOWEVER
Rather than having a click handler you should have an ICommand in your view model for adding a new customer. Then you should bind to command of your button to the ICommand in your view model.
you were binding the CustomerLIst.FirstName which is not walid because innterconent will check for property name customerlist in side the listbox itemssource. and as its not their then it will raise a silent error but wo't show into GUI, what you need to do is just provide the propertyname like firstname and lastname that will work.
well besides your binding in listbox every thing else is ok. just replace you listbox binding as like below.
<TextBlock Grid.Row="0"
Grid.Column="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="List of Customers" />
<ListBox Name="cList"
Grid.Row="1"
Grid.RowSpan="8"
Grid.Column="2"
ItemsSource="{Binding CustomerList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock FontWeight="Bold"
Foreground="Black"
Text="{Binding FirstName}" />
<TextBlock Text=", " />
<TextBlock FontWeight="Bold"
Foreground="Black"
Text="{Binding LastName}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Grid.Row="10"
Grid.Column="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{Binding CustomerList.Count,
StringFormat='Total Customers, ={0}'}" />
better to take command insteed of events.
Your problem is in this line of code:
RaisePropertyChanged("CustomerList");
It doesn't work for collection add/remove events. Take a look at ObservableCollection and Item PropertyChanged.
Keep in mind that in MVVM, you should not have much code (if any) in code behind. Consider using commands.

Resources