What I'm trying to achieve doesn't sounds like rocket science. What I'm trying to create is a custom control to which I could pass a list of UIElements items directly from XAML so each element could be different and embed different objects (grid / textbox / panel etc ... ).
Here is the xaml code I would like to use:
<wpf:TileListDoubleItem>
<wpf:TileListDoubleItem.FrontItem>
<Grid>
<TextBlock FontFamily="Calibri,Verdana" FontSize="16" FontWeight="Bold" Foreground="White" Text="Hello"></TextBlock>
</Grid>
</wpf:TileListDoubleItem.FrontItem>
<wpf:TileListDoubleItem.BackItem>
<Grid>
<TextBlock FontFamily="Calibri,Verdana" FontSize="16" FontWeight="Bold" Foreground="White" Text="World"></TextBlock>
</Grid>
</wpf:TileListDoubleItem.BackItem>
</wpf:TileListDoubleItem>
And here is my custom control code:
public partial class TileListDoubleItem : UserControl, INotifyPropertyChanged
{
private bool _flipped;
internal bool CanFlip { get { return true; } }
private bool flipped
{
get {
return this._flipped;
}
set {
this._flipped = value;
DisplayItem = this._flipped ? BackItem : FrontItem;
}
}
public ObservableCollection<TileSide> Sides { get; set; }
public ICommand FlipCommand;
public TileListDoubleItem()
{
InitializeComponent();
FlipCommand = new FlipCommand(this);
flipped = false;
}
private UIElement displayItem { get; set; }
public UIElement DisplayItem
{
get { return this.displayItem; }
set {
if (this.displayItem != value)
{
this.displayItem = value;
OnPropertyChanged("DisplayItem");
}
}
}
public void Flip()
{
try
{
flipped = !flipped;
}
catch (Exception ex)
{
throw ex;
}
}
public UIElement FrontItem
{
get { return (UIElement)GetValue(FrontItemProperty); }
set { SetValue(FrontItemProperty, value); }
}
public static readonly DependencyProperty FrontItemProperty =
DependencyProperty.Register("FrontItem", typeof(UIElement), typeof(TileListDoubleItem), new UIPropertyMetadata(null));
public UIElement BackItem
{
get { return (UIElement)GetValue(BackItemProperty); }
set { SetValue(BackItemProperty, value); }
}
public static readonly DependencyProperty BackItemProperty =
DependencyProperty.Register("BackItem", typeof(UIElement), typeof(TileListDoubleItem), new UIPropertyMetadata(null));
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
When I run this, both my FrontItem and BackItem are equal to null and are never set to the UIElement (Grid in this example).
I guess what I'm missing must be very obvious to some people.
Thanks in advance for anyone's help here.
Your properies are set as expected. You can confirm this by for example create two TextBlocks that binds to the properties of your control:
<wpf:TileListDoubleItem x:Name="control">
<wpf:TileListDoubleItem.FrontItem>
<Grid>
<TextBlock FontFamily="Calibri,Verdana" FontSize="16" FontWeight="Bold" Foreground="White" Text="Hello"></TextBlock>
</Grid>
</wpf:TileListDoubleItem.FrontItem>
<wpf:TileListDoubleItem.BackItem>
<Grid>
<TextBlock FontFamily="Calibri,Verdana" FontSize="16" FontWeight="Bold" Foreground="White" Text="World"></TextBlock>
</Grid>
</wpf:TileListDoubleItem.BackItem>
</wpf:TileListDoubleItem>
<TextBlock Text="{Binding FrontItem.Children[0].Text, ElementName=control}" />
<TextBlock Text="{Binding BackItem.Children[0].Text, ElementName=control}" />
Obviously the properties won't be set by the time the constructor of TileListDoubleItem returns. The XAML parser needs to instantiate the object before it can set any of its properties, just like you do when you create an instance of a class yourself.
Related
I'm having an issue databinding to a property that is two levels deep in a collection.
The object is structured as such
Collection
--Data
--Name
--Collection
--Name
--Data
So essentially its a collection within a collection, and I can't seem to bind to the name within the contained collection.
I can bind to all the properties of the initial collection, including the collection within it, but as soon as I try to bind to the name property of the internal collection I get bad bindings.
XAML Portion
<TabControl ItemsSource="{Binding Path=BMOverlayCollection}" Grid.Column="0" Grid.Row="4" Grid.ColumnSpan="4">
<TabControl.ItemTemplate>
<!-- this is the header template-->
<DataTemplate>
<TextBlock
Text="{Binding Name}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<!-- this is the body of the TabItem template-->
<DataTemplate>
<TextBlock
Text="{Binding Graphics.Name}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
C# Portion
public class BMGraphicsOverlayCollection : INotifyPropertyChanged, IEnumerable
{
#region Event Property
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private ObservableCollection<NamedOverlay> _namedOverlays;
public ObservableCollection<NamedOverlay> NamedOverlays { get { return _namedOverlays; } set { _namedOverlays = value; OnPropertyChanged(); } }
public BMGraphicsOverlayCollection()
{
_namedOverlays = new ObservableCollection<NamedOverlay>();
}
public void Add(string name, GraphicsOverlay overlay)
{
NamedOverlay mOverlay = new NamedOverlay();
mOverlay.Name = name;
mOverlay.Overlay = overlay;
_namedOverlays.Add(mOverlay);
}
public void Add(string name, GraphicsOverlay overlay, IList<MapGraphic> graphics)
{
NamedOverlay mOverlay = new NamedOverlay();
mOverlay.Name = name;
mOverlay.Overlay = overlay;
mOverlay.Graphics = new ObservableCollection<MapGraphic>(graphics);
_namedOverlays.Add(mOverlay);
}
public IEnumerator GetEnumerator()
{
return _namedOverlays.GetEnumerator();
}
}
public class NamedOverlay : INotifyPropertyChanged
{
#region Event Property
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private string _name;
public string Name { get { return _name; } set { _name = value; OnPropertyChanged(); } }
private GraphicsOverlay _overlay;
public GraphicsOverlay Overlay { get { return _overlay; } set { _overlay = value; OnPropertyChanged(); } }
private ObservableCollection<MapGraphic> _graphics;
public ObservableCollection<MapGraphic> Graphics { get { return _graphics; } set { _graphics = value; OnPropertyChanged(); } }
}
}
And the MapGraphic pertinent part
private string _name;
public string Name
{
get
{
if (_name == null)
{
return "Unnamed";
} else
{
return _name;
}
}
set
{
_name = value; OnPropertyChanged();
}
}
Thanks in advance for the help.
According to your code, Your data structure was NamedOverlays[].Graphics[].Name, but your binding path was NamedOverlays[].Graphics.Name. That's the reason of the bad binding. Change
<TextBlock Text="{Binding Graphics.Name}" />
to (if you want to show all names in Graphics)
<ListBox ItemsSource="{Binding Graphics}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
or (if you just want to show 1st name in graphics)
<TextBlock Text="{Binding Graphics[0].Name}" />
will fix the problem.
I have a TextBlock in XAML that's bound to a property called EditsWarning:
<TextBlock DockPanel.Dock="Top" Text="{Binding EditsWarning, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Style="{DynamicResource Esri_TextBlockRegular}" HorizontalAlignment="Left" FontSize="14" FontWeight="DemiBold" VerticalAlignment="Center" Margin="10,0,10,5" TextWrapping="WrapWithOverflow"/>
The Definition for the EditsWarning Property is here:
public string EditsWarning
{
get { return editsWarningMessage; }
set
{
SetProperty(ref editsWarningMessage, value, () => this.EditsWarning);
}
}
The EditsWarning Property is set to an instance of a class like this:
editsWarning = new OutstandingEditsTextBlock();
editsWarningMessage = editsWarning.EditsWarningMessage.ToString();
And the OutstandingEditsTextBlock class is here, and implements INotifyPropertyChanged
internal class OutstandingEditsTextBlock : INotifyPropertyChanged
{
private string editsWarning;
public OutstandingEditsTextBlock()
{
if (Project.Current.HasEdits)
{
this.editsWarning = "This session/version has outstanding edits.";
}
else
{
this.editsWarning = string.Empty;
}
}
public event PropertyChangedEventHandler PropertyChanged;
public string EditsWarningMessage
{
get { return this.editsWarning; }
set
{
this.editsWarning = value;
this.OnPropertyChanged("EditsWarningMessage");
}
}
public void OnPropertyChanged(string propertyName)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
I noticed that I can get it to display either value, however, I can never get it to update in the same debugging session. In fact, it looks like the setter for the public property is never hit.
Can someone please help me figure out what I'm doing wrong?
Thank you.
I know I should use the MVVM pattern but I'm trying to get step by step closer to it. So here is my Listbox:
<ListBox x:Name="BoardList" ItemsSource="{Binding notes}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<TextBox IsReadOnly="True" ScrollViewer.VerticalScrollBarVisibility="Visible" Text="{Binding text}" TextWrapping="Wrap" Foreground="DarkBlue"></TextBox>
<AppBarButton Visibility="{Binding visibility}" Icon="Globe" Click="OpenInBrowser" x:Name="Link"></AppBarButton>
<AppBarButton Icon="Copy" Click="Copy"></AppBarButton>
<AppBarButton Icon="Delete" Click="Delete"></AppBarButton>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
In the Mainpage.xaml.cs I declare the following:
ObservableCollection<BoardNote> notes = new ObservableCollection<BoardNote>();
So if I understood this right I don't need to care about the "INotifyCollectionChanged" stuff because I'm using an observablecollection?
So I got for example a textbox like this:
<Textbox x:Name="UserInputNote" Placeholdertext="Type in a text for your note"></Textbox>
And a button to Add the new note to the ObservableCollection and the click event is just like this:
notes.Add(new BoardNote(UserInputNote.Text));
So now the UI should update every time the user clicks the button to save a new note. But nothing happens. What did I do wrong?
If you need it here is the BoardNote class:
class BoardNote
{
public string text
{
get; set;
}
public BoardNote(string text)
{
this.text = text;
}
public Visibility visibility
{
get
{
if (text.StartsWith("http"))
return Visibility.Visible;
else
return Visibility.Collapsed;
}
}
}
You need to implement INotifyPropertyChanged. Here's one way of doing it.
Create this NotificationObject class.
public class NotificationObject : INotifyPropertyChanged
{
protected void RaisePropertyChanged<T>(Expression<Func<T>> action)
{
var propertyName = GetPropertyName(action);
RaisePropertyChanged(propertyName);
}
private static string GetPropertyName<T>(Expression<Func<T>> action)
{
var expression = (MemberExpression)action.Body;
var propertyName = expression.Member.Name;
return propertyName;
}
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Then your BoardNote class will inherit it this way:
class BoardNote : NotificationObject
{
private string _text
public string Text
{
get {return _text;}
set
{
if(_text == value) return;
_text = value;
RaisePropertyChanged(() => Text);
}
}
public BoardNote(string text)
{
this.text = text;
}
public Visibility visibility
{
get
{
if (text.StartsWith("http"))
return Visibility.Visible;
else
return Visibility.Collapsed;
}
}
}
I have a TreeView with Binding, but in the TreeView only 1st level items are shown. I need a treeview =) I broke my head what is wrong.
Here is my code:
MainWindow.xaml
<TreeView Margin="2.996,10,214,10" ItemsSource="{Binding Path=Urls}" Grid.Column="1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate>
<Grid>
<Rectangle Fill="{Binding Path=Color}" HorizontalAlignment="Left" Stroke="Black" VerticalAlignment="Top" Height="20" Width="20"/>
<TextBlock Text="{Binding Path=AbsoluteUrl}" Margin="25,0,0,0" />
</Grid>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=AbsoluteUrl}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
MainViewModel.cs (part)
public ObservableCollection<Url> Urls { get; set; }
public MainWindowViewModel()
{
Urls = new ObservableCollection<Url>();
}
Url.cs
class Url : INotifyPropertyChanged
{
public Url() { }
public Url(string absoluteUrl, bool isBroken, string color)
{
AbsoluteUrl = absoluteUrl;
IsBroken = isBroken;
Color = color;
}
enum Status { Working, Broken };
private ObservableCollection<Url> childUrlsValue = new ObservableCollection<Url>();
public ObservableCollection<Url> ChildUrls
{
get
{
return childUrlsValue;
}
set
{
childUrlsValue = value;
}
}
private string _absoluteUrl;
public string AbsoluteUrl
{
get { return _absoluteUrl; }
set
{
if (_absoluteUrl != value)
{
_absoluteUrl = value;
OnPropertyChanged("AbsoluteUrl");
}
}
}
private bool _isBroken;
public bool IsBroken
{
get { return _isBroken; }
set
{
if (_isBroken != value)
{
_isBroken = value;
OnPropertyChanged("IsBroken");
}
}
}
private string _color;
public string Color
{
get { return _color; }
set
{
if (_color != value)
{
_color = value;
OnPropertyChanged("Color");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And just about this i'm adding items to Urls:
Url DataGridTopic = new Url(startUrl.ToString(), true, "red");
DataGridTopic.ChildUrls.Add(
new Url(startUrl.ToString(), true, "red"));
DataGridTopic.ChildUrls.Add(
new Url(startUrl.ToString(), true, "red"));
DataGridTopic.ChildUrls.Add(
new Url(startUrl.ToString(), true, "red"));
Urls.Add(DataGridTopic);
You will have to tell the HierarchicalDataTemplate where to get the child items of a node from by using its ItemsSource property.
In your case:
<HierarchicalDataTemplate
DataType="{x:Type my:Url}"
ItemsSource="{Binding Path=ChildUrls}"
>
...
</HierarchicalDataTemplate>
Note also the usage od the DataType attribute, which often will become a necessity if the levels of the tree are made of different object types (a tree of directories and files would be such an example). However, i am not sure whether this would apply to your scenario or not.
I am working on a windows phone application that uses a local database and MVVM. My listbox is not showing the WeatherList that it is binded to. I am adding a single WeatherItem to the local database in the App.xaml.cs file and it's being added successfully, but it is not showing up in the listbox when running the app. I would really appreciate any help. I have the following setup:
MainPage.xaml:
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="ForecastListItemTemplate">
<StackPanel Orientation="Horizontal" Margin="0, 400, 0, 0" Width="480" Height="100">
<StackPanel Width="190" VerticalAlignment="Center">
<TextBlock HorizontalAlignment="Center" Text="{Binding Path=DayOfWeek}" FontFamily="Segoe WP" FontWeight="ExtraBold" FontSize="36" Foreground="#545d61"></TextBlock>
<TextBlock HorizontalAlignment="Center" Text="{Binding Path=ItemDay}" FontFamily="Segoe WP Light" FontSize="36" Foreground="#545d61"></TextBlock>
</StackPanel>
<Image Height="100" Width="100" Source="{Binding Path=ImageSource}"></Image>
<StackPanel Width="190" VerticalAlignment="Center">
<StackPanel HorizontalAlignment="Center" Orientation="Horizontal">
<TextBlock Text="↑" FontFamily="Segoe WP" FontWeight="ExtraBold" FontSize="36" Foreground="#545d61"></TextBlock>
<TextBlock HorizontalAlignment="Center" Margin="4, 0, 4, 0" Text="{Binding Path=High}" FontFamily="Segoe WP" FontWeight="ExtraBold" FontSize="36" Foreground="#0da5d0"></TextBlock>
<TextBlock Text="↓" FontFamily="Segoe WP" FontWeight="ExtraBold" FontSize="36" Foreground="#545d61"></TextBlock>
<TextBlock HorizontalAlignment="Center" Margin="4, 0, 4, 0" Text="{Binding Path=Low}" FontFamily="Segoe WP" FontWeight="ExtraBold" FontSize="36" Foreground="#0da5d0"></TextBlock>
</StackPanel>
<TextBlock HorizontalAlignment="Center" Text="{Binding Path=Condition}" FontFamily="Segoe WP Light" FontSize="24" Foreground="#545d61"></TextBlock>
</StackPanel>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="#e1e4e4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ListBox
x:Name="WeatherListBox"
ItemsSource="{Binding WeatherList}"
Margin="0, 400, 0, 96"
Width="480"
ItemTemplate="{StaticResource ForecastListItemTemplate}">
</ListBox>
</Grid>
WeatherViewModel.cs
public class WeatherViewModel : INotifyPropertyChanged
{
// LINQ to SQL data context for the local database.
private ToDoDataContext weatherDB;
// Class constructor, create the data context object.
public WeatherViewModel()
{
weatherDB = new ToDoDataContext();
}
// All to-do items.
private ObservableCollection<WeatherItem> _weatherList;
public ObservableCollection<WeatherItem> WeatherList
{
get { return _weatherList; }
set
{
_weatherList = value;
NotifyPropertyChanged("WeatherList");
}
}
// Write changes in the data context to the database.
public void SaveChangesToDB()
{
weatherDB.SubmitChanges();
}
// Query database and load the collections and list used by the pivot pages.
public void LoadCollectionsFromDatabase()
{
// Specify the query for all to-do items in the database.
var weatherItemsInDB = from WeatherItem weather in weatherDB.Forecasts
select weather;
// Query the database and load all to-do items.
WeatherList = new ObservableCollection<WeatherItem>(weatherItemsInDB);
}
// Add a to-do item to the database and collections.
public void AddWeatherItem(WeatherItem newWeatherItem)
{
// Add a to-do item to the data context.
weatherDB.Forecasts.InsertOnSubmit(newWeatherItem);
// Save changes to the database.
weatherDB.SubmitChanges();
// Add a to-do item to the "all" observable collection.
WeatherList.Add(newWeatherItem);
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify Silverlight that a property has changed.
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
ToDoDataContext.cs
public class ToDoDataContext : DataContext
{
// Pass the connection string to the base class.
public ToDoDataContext()
: base("Data Source=isostore:/AppDB.sdf")
{ }
public ToDoCategory activeCategory;
// Specify a table for the to-do items.
public Table<ToDoItem> Items;
// Specify a table for the categories.
public Table<ToDoCategory> Categories;
//Weather stuff
public WeatherItem currentWeather;
// Specify a table for the to-do items.
public Table<WeatherItem> Forecasts;
}
[Table]
public class WeatherItem : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property, and database column.
private int _weatherItemId;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int WeatherItemId
{
get { return _weatherItemId; }
set
{
if (_weatherItemId != value)
{
NotifyPropertyChanging("WeatherItemId");
_weatherItemId = value;
NotifyPropertyChanged("WeatherItemId");
}
}
}
// Define item name: private field, public property, and database column.
private string _itemDay;
[Column]
public string ItemDay
{
get { return _itemDay; }
set
{
if (_itemDay != value)
{
NotifyPropertyChanging("ItemDay");
_itemDay = value;
NotifyPropertyChanged("ItemDay");
}
}
}
private string _dayOfWeek;
[Column]
public string DayOfWeek
{
get { return _dayOfWeek; }
set
{
if (_dayOfWeek != value)
{
NotifyPropertyChanging("DayOfWeek");
_dayOfWeek = value;
NotifyPropertyChanged("DayOfWeek");
}
}
}
// Define completion value: private field, public property, and database column.
private string _high;
[Column]
public string High
{
get { return _high; }
set
{
if (_high != value)
{
NotifyPropertyChanging("High");
_high = value;
NotifyPropertyChanged("High");
}
}
}
private string _low;
[Column]
public string Low
{
get { return _low; }
set
{
if (_low != value)
{
NotifyPropertyChanging("Low");
_low = value;
NotifyPropertyChanged("Low");
}
}
}
private string _condition;
[Column]
public string Condition
{
get { return _condition; }
set
{
if (_condition != value)
{
NotifyPropertyChanging("Condition");
_condition = value;
NotifyPropertyChanged("Condition");
}
}
}
private string _imageSource;
[Column]
public string ImageSource
{
get { return _imageSource; }
set
{
if (_imageSource != value)
{
NotifyPropertyChanging("ImageSource");
_imageSource = value;
NotifyPropertyChanged("ImageSource");
}
}
}
// Version column aids update performance.
[Column(IsVersion = true)]
private Binary _version;
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify that a property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region INotifyPropertyChanging Members
public event PropertyChangingEventHandler PropertyChanging;
// Used to notify that a property is about to change
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
#endregion
}
Mainpage.xaml.cs
// Constructor
public MainPage()
{
InitializeComponent();
this.DataContext = App.WeatherViewModel;
}
App.xaml.cs
public partial class App : Application
{
private static ToDoViewModel viewModel;
public static ToDoViewModel ViewModel
{
get { return viewModel; }
}
private static WeatherViewModel weatherViewModel;
public static WeatherViewModel WeatherViewModel
{
get { return weatherViewModel; }
}
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Disable the application idle detection by setting the UserIdleDetectionMode property of the
// application's PhoneApplicationService object to Disabled.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
// Create the database if it does not exist.
using (ToDoDataContext db = new ToDoDataContext())
{
if (db.DatabaseExists() == false)
{
// Create the local database.
db.CreateDatabase();
// Prepopulate the categories.
db.Categories.InsertOnSubmit(new ToDoCategory { Name = "Home" });
db.Categories.InsertOnSubmit(new ToDoCategory { Name = "Work" });
db.Categories.InsertOnSubmit(new ToDoCategory { Name = "School" });
db.Forecasts.InsertOnSubmit(new WeatherItem
{
DayOfWeek = "Mon",
ItemDay = "Sept 4",
Condition = "Mostly Sunny",
High = "105",
Low = "88",
ImageSource = "images/Weather/45.png"
});
// Save categories to the database.
db.SubmitChanges();
}
}
// Create the ViewModel object.
viewModel = new ToDoViewModel();
weatherViewModel = new WeatherViewModel();
// Query the local database and load observable collections.
viewModel.LoadCollectionsFromDatabase();
weatherViewModel.LoadCollectionsFromDatabase();
}
Thanks!
Did you check out the output window for data binding errors?
And in the ctor of the main page, is App.WeatherViewModel already not-null?
You add
WeatherListBox.DataContext = WeatherList;
And you modify binding with
ItemsSource="{Binding}"