I've just started learning WPF desktop application. I've written some let say easy code below, to excercise binding operation.
The problem is:
I wanted type sth in TextBox and see it simultaneously in TextBlock, but after compiling and running app, controls on form do not behave as I described.
Can anybody help me to fix it?
MainWindow.xaml:
<Window x:Class="Napisy.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:Napisy"
xmlns:mv="clr-namespace:Napisy.ModelWidoku"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<mv:NapisyModelWidoku x:Key="napisyModelWidoku"/>
</Window.Resources>
<Grid DataContext="{StaticResource napisyModelWidoku}">
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<TextBox Grid.Row="1" Margin="10,10,10,10" Text="{Binding Path=Tekst,Mode=TwoWay}"/>
<TextBlock Grid.Row="2" Margin="10,10,10,10" Text="{Binding Path=Wyswietl,Mode=OneWay}"/>
</Grid>
</Window>
ViewModel code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Napisy.Model;
using System.ComponentModel;
namespace Napisy.ModelWidoku
{
public class NapisyModelWidoku : INotifyPropertyChanged
{
NapisyModel model = new NapisyModel();
public string Tekst
{
get
{
return model.Tekst;
}
set
{
model.Tekst = value;
OnPropertyChanged(nameof(Tekst));
OnPropertyChanged(nameof(Wyswietl));
}
}
public string Wyswietl
{
get
{
return model.Tekst;
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string nazwa)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nazwa));
}
}
}
Model Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Napisy.Model
{
public class NapisyModel
{
public string Tekst { get; set; }
}
}
EDIT:
Problem description,
before class NapisyModelWidoku, acces modificator public added,
added OnPropertyChanged(nameof(Tekst));
instead OnPropertyChanged("Wyswietl"); used OnPropertyChanged(nameof(Wyswietl));
After typing text into TextBox still TextBlock not refresh automatically. Still hope I receive tips. Thanks
Along with adding UpdateSourceTrigger in both bindings, make below change also,
public string Tekst
{
get
{
return model.Tekst;
}
set
{
model.Tekst = value;
OnPropertyChanged("Tekst");
OnPropertyChanged("Wyswietl");
}
}
I ran your code and it does not work because PropertyChanged is null. You have to set the datacontext of your view so that the PropertyChangedEventHandler can be binded.
Add in your code behind, i-e MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
this.DataContext = new NapisyModelWidoku();
}
Related
I am making a To-do List application for one of my classes. Now I have tried in a console app to update objects (of TaskModels a type I defined) inside an observable collection and it has seemed to work. But now I am trying to update the entries inside the observable collection. I have wrote some code that I thought was going to change the value but it did not change the value in the ListBox I will include the code below for TaskModel.
Originally I was wanting to have the edit button open a new window that allowed the user to input what the wanted the task to be and then they press a button maybe called change task and it sends it back to the original window. But for simpleness at the moment I would like to change with the textbox in the user control in the main window.
I am also pretty new to making apps in WPF so this is all pretty new to me and I am trying to learn it all.
Below is my TaskModel and the only thing it does is get and set the TaskName.
namespace ToDoList.Model
{
public class TaskModel
{
private string taskName;
public string TaskName {
get { return taskName; }
set { taskName = value; }
}
}
}
I wrote the following code hoping that it would allow me to change the value of the TaskName but it does not seem to be working. Is there anyhting else that I should add to the code for it change the TaskName properly? Any tips or anything that could help me with this problem.
Below is the XAML code for my main window. It is a really simple UI, it features a ListBox which uses an ObservableCollection as its itemsource and when the listbox has a new item put into it has a checkbox to the left of it.
Below I will include the main window XAML and the C# code.
<Window x:Class="ToDoList.DemoMainWindow"
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:ToDoList"
mc:Ignorable="d"
Title="The To-Do List" Height="500" Width="500" FontSize="22"
Background="White">
<Grid Margin="10" Background="BlueViolet">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2">
<TextBlock>Tasks to do:</TextBlock>
<!-- <TextBlock>Blah blah</TextBlock> -->
<!-- <local:UCLabelTextBxInput x:Name="TxtUCSaveToFileLocation" Title="Save to File Location" MaxLength="50"></local:UCLabelTextBxInput> -->
<ListBox x:Name="LstBoxTasks" MinHeight="200" MaxHeight="200" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Mode=OneWay}" Content="{Binding TaskName, Mode=TwoWay}" FontSize="14"></CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<local:UCLabelTextBxInput x:Name="TxtUCEnteredTask" Title="Enter Task Here:" MaxLength="50"></local:UCLabelTextBxInput>
<Button x:Name="BtnAddTask" Click="BtnAddTask_Click" Background="Chocolate">Add Task to List</Button>
</StackPanel>
<Button Grid.Column="0" Grid.Row="1" Margin="0,10,20,0" x:Name="btnDeleteTask" Click="BtnDeleteTask_Click" Background="Chocolate">Delete Task</Button>
<Button Grid.Column="1" Grid.Row="1" Margin="20,10,0,0" Background="Chocolate" Click="BtnEditTask_Click">Edit Task</Button>
<Button Grid.Column="0" Grid.Row="2" Margin="0,10,0,10" Grid.ColumnSpan="2" Background="Chocolate" Click="BtnHelp_Click">Help</Button>
</Grid>
</Window>
Then finally here is the C# code:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ToDoList.Model;
namespace ToDoList
{
/// <summary>
/// Interaction logic for DemoMainWindow.xaml
/// </summary>
public partial class DemoMainWindow : Window
{
SaveDataModel saveDataModel = new SaveDataModel();
ObservableCollection<TaskModel> tasksModels = new ObservableCollection<TaskModel>();
public DemoMainWindow()
{
InitializeComponent();
TxtUCEnteredTask.txtLimitedInput.Text = "Do the dishes";
LstBoxTasks.ItemsSource = tasksModels;
}
private void BtnAddTask_Click(object sender, RoutedEventArgs e)
{
tasksModels.Add(new TaskModel() { TaskName = TxtUCEnteredTask.txtLimitedInput.Text });
}
private void BtnDeleteTask_Click(object sender, RoutedEventArgs e)
{
if(LstBoxTasks.SelectedItem != null)
{
tasksModels.Remove(LstBoxTasks.SelectedItem as TaskModel);
}
}
private void BtnHelp_Click(object sender, RoutedEventArgs e)
{
HelpWindow helpWindow = new HelpWindow();
helpWindow.Show();
}
private void BtnEditTask_Click(object sender, RoutedEventArgs e)
{
if (LstBoxTasks.SelectedItem != null)
{
tasksModels[LstBoxTasks.SelectedIndex].TaskName = TxtUCEnteredTask.txtLimitedInput.Text;
}
}
}
}
Your property TaskName is not calling the OnPropertyChanged() method that notifies your view that the name changed.
You can do something like that:
private string taskName;
public string TaskName {
get { return taskName; }
set {
if( value != taskName) {
taskName = value;
OnPropertyChanged("TaskName");
}
}
}
protected void OnPropertyChanged(string name) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
Remarks:
The best way to do WPF is to do MVVM.
You should check out this link : https://www.codeproject.com/Tips/806587/Basic-MVVM-Listbox-Binding-in-WPF
I have a list of users below:
public ObservableCollection<User> Users
{
get;
private set;
}
And in the XAML file, I am binding Users to the grid control
<dxg:GridControl x:Name="grid"
ItemsSource="{Binding Users}"
SelectedItem="{Binding CurrentUser}"
...
>
<dxg:GridControl.Columns>
<dxg:GridColumn FieldName="Name" Header="name" />
<dxg:GridColumn FieldName="Mobile" Header="mobile"/>
</dxg:GridControl.Columns>
</dxg:GridControl>
Until here everything is Ok and the binding works correctly.
Now I want to bind special users. for example, users where the length of their names is less than 5.
private ObservableCollection<TUserItem> usersVisible;
public ObservableCollection<User> UsersVisible
{
get
{
return Users.Where(u => u.name.Length < 5).ToObservableCollection();
}
set
{
usersVisible = value;
OnPropertyChanged();
}
}
but it doesn't work and the XAML grid control doesn't update.
If I return
return Users;
instead of
return Users.Where(u => u.name.Length < 5).ToObservableCollection();
everything is ok and the binding works correctly.
What's your suggestion?
Thanks
If you look up the source code of the method ToObservableCollection, you will find out that it returns a new collection. So your binding now points to the old objects still and you will not see any change. I have created a repo of a WPF sample for you that you can run here:
https://github.com/toreaurstadboss/WpfFilteredCollection
First I define a User class for demonstration:
namespace WpfFilteredCollection
{
public class User
{
public string Name { get; set; }
public bool IsAdmin { get; set; }
}
}
I then create a MainWindowViewModel which I add the INotifyPropertyChanged interface to signal change to the UI and also use ICollectionViewSource. This is an interface which together with CollectionViewSource supports sorting and filtering. It is part of System.Windows.Data and has been around for a long time.
MainWindowViewModel looks like this:
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Data;
namespace WpfFilteredCollection
{
public class MainWindowViewModel : INotifyPropertyChanged
{
private readonly ICollectionView _usersView;
public event PropertyChangedEventHandler? PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public ICollectionView Users
{
get { return _usersView; }
}
public MainWindowViewModel()
{
IList<User> users = GetUsers();
_usersView = CollectionViewSource.GetDefaultView(users);
_usersView.Filter = (object u) => u != null && (u as User)?.Name?.Length <= FilterNameLength;
FilterNameLength = 6;
}
private IList<User> GetUsers()
{
return new List<User>
{
new User { Name = "Bob", IsAdmin = false },
new User { Name = "Alice", IsAdmin = false }
};
}
private int _filterNameLength = 0;
public int FilterNameLength
{
get { return _filterNameLength; }
set
{
if (_filterNameLength != value)
{
_filterNameLength = value;
RaisePropertyChanged("FilterNameLength");
_usersView.Refresh();
}
}
}
}
}
MainWindow.xaml.cs code behind looks like this, setting DataContext to an instance of the view model or 'VM'.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfFilteredCollection
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
}
And we have the UI, which only uses standard stuff (components) in WPF. The textbox looks terrible, as WPF lacks a proper built-in numeric textbox without having to add behaviors.
<Window x:Class="WpfFilteredCollection.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:WpfFilteredCollection"
mc:Ignorable="d"
Title="MainWindow" Height="300" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Label Margin="10" Height="28" Grid.Row="0">Filter on length (name of user): </Label>
<TextBox Margin="10" Width="100" HorizontalAlignment="Left" Background="AliceBlue" Grid.Row="1" Height="28" Text="{Binding FilterNameLength, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<ListView Grid.Row="2" Margin="10" ItemsSource="{Binding Users}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="300" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="IsAdmin" Width="100" DisplayMemberBinding="{Binding IsAdmin}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
But my solution uses standard parts of the .net framework and should therefore be used in many different scenarios. For larger amounts of data, you might consider using more advanced collections and components, that supports 'virtualization', i.e. rendering only visible rows and so on.
To test out the solution, just alter the textbox value from 6 down to 4 to only see Bob and not Bob and Alice.
Note that I have not used an observable collection, but a plain list. You can see a sample of an observable collection using collection view source in this answer on SO:
Binding a CollectionViewSource to ObservableCollection
I'm trying to reproduce a MVVM tutorial for WPF but applying it to UWP. But I've done everything in the tutorial I believe right the exact same code shown at the tutorial.
But when I ran the code I kept getting a StackOverflowException which is caused because the MainPageView keeps initializing again and again, until the exception is thrown.
The thing is I'm kinda knew at MVVM and I wish to master it, so can somebody please explain me why am I getting this?
I'll leave the code of each one of my classes and views.
This is my MainPageView.Xaml:
<Page
x:Class="MVVMHierarchiesDemo.MainPageView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MVVMHierarchiesDemo"
xmlns:views="using:MVVMHierarchiesDemo.Views"
xmlns:viewmodel="using:MVVMHierarchiesDemo.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<!--Anytime the current view model is set to an instance of a CustomerListViewModel,
it will render out a CustomerListView with the ViewModel is hooked up. It’s an order ViewModel,
it'll render out OrderView and so on.
We now need a ViewModel that has a CurrentViewModel property and some logic and commanding
to be able to switch the current reference of ViewModel inside the property.-->
<Page.DataContext>
<local:MainPageView/>
</Page.DataContext>
<Page.Resources>
<DataTemplate x:Key="CustomerTemplate" x:DataType="viewmodel:CustomerListViewModel">
<views:CustomerListView/>
</DataTemplate>
<DataTemplate x:Key="OrderTemplate" x:DataType="viewmodel:OrderViewModel">
<views:OrderView/>
</DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid x:Name="NavBar"
Grid.Row="0">
<Button Content="Customers"
Command="{Binding NavCommand}"
CommandParameter="customers"
Grid.Column="0"
Grid.Row="0"/>
<Button Content="Orders"
Command="{Binding NavCommand}"
CommandParameter="orders"
Grid.Column="2"
Grid.Row="0"/>
</Grid>
<Grid x:Name="MainContent"
Grid.Row="1">
<ContentControl Content="{Binding CurrentViewModel}"/>
</Grid>
</Grid>
</Page>
This is my code-behind MainPageView.xaml.cs - here is where the StackoverflowException is thrown in the constructor it keeps calling it.
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace MVVMHierarchiesDemo
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPageView : Page
{
public MainPageView()
{
this.InitializeComponent();
}
}
}
This is my BindableBase.cs as the tutorial shows:
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace MVVMHierarchiesDemo
{
/*The main idea behind this class is to encapsulate the INotifyPropertyChanged implementation
* and provide helper methods to the derived class so that they can easily trigger the appropriate notifications.
* Following is the implementation of BindableBase class.*/
public class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void SetProperty<T>(ref T member, T val, [CallerMemberName]string propertyName = null)
{
if (object.Equals(member, val))
return;
member = val;
OnPropertyChanged(propertyName);
}
}
}
This is MyCommand.cs or better known as the relay command pattern:
using System;
using System.Windows.Input;
namespace MVVMHierarchiesDemo
{
/* Now it's time to actually start doing some view switching using our CurrentViewModel property.
* We just need some way to drive the setting of this property. And we're going to make it so that
* the end user can command going to the customer list or to the order view. First add a new class
* in your project which will implement the ICommand interface. Following is the implementation of
* ICommand interface.*/
public class MyCommand<T> : ICommand
{
Action<T> _TargetExecuteMethod;
Func<T, bool> _TargetCanExecuteMethod;
public MyCommand(Action<T> targetExecuteMethod)
{
_TargetExecuteMethod = targetExecuteMethod;
}
public MyCommand(Action<T> targetExecuteMethod, Func<T,bool> targetCanExecuteMethod)
{
_TargetExecuteMethod = targetExecuteMethod;
_TargetCanExecuteMethod = targetCanExecuteMethod;
}
public event EventHandler CanExecuteChanged = delegate { };
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
bool ICommand.CanExecute(object parameter)
{
if (_TargetCanExecuteMethod != null)
{
T tparam = (T)parameter;
return _TargetCanExecuteMethod(tparam);
}
if (_TargetExecuteMethod != null)
return true;
return false;
}
void ICommand.Execute(object parameter)
{
if(_TargetExecuteMethod!=null)
{
T tparam = (T)parameter;
_TargetExecuteMethod(tparam);
}
}
}
}
This is my usercontrol for OrdersView.xaml:
<UserControl
x:Class="MVVMHierarchiesDemo.Views.OrderView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MVVMHierarchiesDemo.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<TextBlock Text="Order View"/>
</Grid>
</UserControl>
This is my user control CustomerListView.xaml:
<UserControl
x:Class="MVVMHierarchiesDemo.Views.CustomerListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MVVMHierarchiesDemo.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<TextBlock Text="Customer List View"/>
</Grid>
</UserControl>
This is my OrderViewModel:
namespace MVVMHierarchiesDemo.ViewModel
{
/*Derive all of your ViewModels from BindableBase class.*/
public class OrderViewModel : BindableBase
{
}
}
This is my CustomerViewModel:
namespace MVVMHierarchiesDemo.ViewModel
{
/*Derive all of your ViewModels from BindableBase class.*/
public class CustomerListViewModel : BindableBase
{
}
}
Finally this is my MainPageViewModel:
namespace MVVMHierarchiesDemo.ViewModel
{
/*Derive all of your ViewModels from BindableBase class.*/
public class MainPageViewModel : BindableBase
{
public MainPageViewModel()
{
NavCommand = new MyCommand<string>(OnNavigation);
}
private CustomerListViewModel _customerListViewModel = new CustomerListViewModel();
private OrderViewModel _orderViewModel = new OrderViewModel();
private BindableBase _currentViewModel;
public BindableBase CurrentViewModel
{
get
{
return _currentViewModel;
}
set
{
SetProperty(ref _currentViewModel, value);
}
}
public MyCommand<string> NavCommand { get; private set; }
private void OnNavigation(string destination)
{
switch (destination)
{
case "orders":
{
CurrentViewModel = _orderViewModel;
break;
}
case "customers":
default:
CurrentViewModel = _customerListViewModel;
break;
}
}
}
}
and lastly I think the MainPageView is the one causing the infinite looping but I don't understand why?
If somebody could be so kind to tell me what I am doing wrong on UWP?
Also I could use MVVM Light or MVVMCross I'm not interested on those solutions I want to learn MVVM by hand and later on i might check those frameworks.
It's because in your MainPageView.xaml you have this:
<Page.DataContext>
<local:MainPageView/>
</Page.DataContext>
So every MainPageview creates a nested MainPageView as its DataContext. These are created until you blow the stack.
I think you meant to put a MainPageViewModel in here.
When I click the 'Add Some Thing' button on this simple Win Phone 8 application (built with VS 2012 Pro - its what I have), nothing happens. Why?
The repo of this example code is on bitbucket.org at:
TestItemsControlInWinPhone8App
The MainPage.xaml contains:
<phone:PhoneApplicationPage
x:Class="TestItemsControlInWinPhone8App.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button x:Name="AddSomeThing"
Content="Add Some Thing"
Grid.Row="0"
Click="AddSomeThing_Click"/>
<ItemsControl x:Name="LotsOfThingsItemsControl"
Grid.Row="1"
ItemsSource="{Binding Mode=OneWay}"
FontSize="{StaticResource PhoneFontSizeSmall}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Height="Auto" Width="Auto"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Background="Orange">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Path=Id, Mode=OneWay}"/>
<TextBlock Grid.Row="1"
Text="------------------------"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
</Grid>
</Grid>
</phone:PhoneApplicationPage>
Please note that ItemsControl ItemsSource="{Binding Path=Things} has also been tried as just plain ItemsControl ItemsSource="{Binding}".
Both have the same result; the first five Thing objects display and clicking the "Add Some Thing" button adds another Thing to LotsOfThings.
The contents of the DataTemplate being a TextBlock do, in fact, display the first 5 Thing objects.
But clicking the button does NOT update the display, which persists in displaying only the original 5 Thing objects.
The code behind (MainPage.xaml.cs) reads:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using TestItemsControlInWinPhone8App.Resources;
namespace TestItemsControlInWinPhone8App
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
this.DataContext = new LotsOfThings(5);
}
private void AddSomeThing_Click(object sender, RoutedEventArgs e)
{
LotsOfThings lot = this.DataContext as LotsOfThings;
lot.Add(new Thing());
}
}
}
Note that in the Page constructor this.DataContext = new LotsOfThings(5); works and when the Page first displays, 5 Thing objects are displayed.
To be clear, what doesn't work is that a latter call of the AddSomeThing_click() button handler will add another Thing to LotsOfThings but only the original 5 Thing objects display; nothing more, even if there are many more Thing objects present on LotsOfThings according to the debugger.
What I notice using the debugger is that whenever OnPropertyChanged(...) is called handler is null. That is clearly important but I have no idea why that is happening having at this point followed all the remedial help I can find searching the web.
Why?
Contents of Thing.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestItemsControlInWinPhone8App
{
public class Thing : INotifyPropertyChanged
{
private string _Id = Guid.NewGuid().ToString();
public string Id
{
get
{
return _Id;
}
set { }
}
#region Constructor
public Thing()
{
this.OnPropertyChanged( "Id");
}
#endregion
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string pPropertyName)
{
System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(pPropertyName));
}
}
#endregion
}
}
Contents of LotsOfThings.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestItemsControlInWinPhone8App
{
class LotsOfThings : INotifyPropertyChanged, IList<Thing>
{
private List<Thing> _things = new List<Thing>();
public List<Thing> Things
{
get {
return _things;
}
set { }
}
public LotsOfThings( int pNumberOfThings)
{
for( int x = 0; x < pNumberOfThings; x++){
this.Add( new Thing());
}
OnPropertyChanged("Things");
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string pName)
{
System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(pName));
}
}
#endregion
#region IList<T> methods
public int IndexOf(Thing item)
{
return _things.IndexOf(item);
}
public void Insert(int index, Thing item)
{
_things.Insert(index, item);
}
public void RemoveAt(int index)
{
_things.RemoveAt(index);
}
public Thing this[int index]
{
get
{
return _things[index];
}
set
{
_things[index] = value;
}
}
public void Add(Thing item)
{
_things.Add(item);
OnPropertyChanged("Things");
}
public void Clear()
{
_things.Clear();
}
public bool Contains(Thing item)
{
return _things.Contains(item);
}
public void CopyTo(Thing[] array, int arrayIndex)
{
_things.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _things.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(Thing item)
{
return _things.Remove(item);
}
public IEnumerator<Thing> GetEnumerator()
{
return _things.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _things.GetEnumerator();
}
#endregion
}
}
If you need to just download the application or look at it with a better interface you can find it here:
TestItemsControlInWinPhone8App
Thank you.
PS. I have read and, I think, followed all the advice I can find on Stackoverflow and elsewhere on the net about null handlers passed into OnPropertyChanged() methods and usage of ItemsControl that I can find.
_things needs to be ObservableCollection<Thing>. List<T> doesn't implement INotifyCollectionChanged, and hence doesn't raise notifications when its contents change. ObservableCollection<Thing> does, which will enable the UI to know when it needs to add items to the list.
The simple, easy, standard way of doing things is to expose an ObservableCollection as a property. If you replace the whole collection with a new one, raise PropertyChanged("Things"); when items are added/removed, the ObservableCollection will raise appropriate events without your needing to do anything. Experienced WPF folks reading your code will know what they're looking at.
To get it working the way you had in mind, you would have to call OnPropertyChanged("Things") in the methods that alter the Things collection; I haven't tested that, but I think it ought to work (the reason it might not is that the actual collection object returned by Things has not changed; the control might see that and choose not to update; but as I said I haven't tested that). Then you could bind Things to an ItemsSource on a control and maybe it ought to work. But then you could have other classes altering Things, because it's public. It would be a mess to try to chase down all the loose ends. Much easier to use ObservableCollection.
If you want to bind LotsOfThings itself to ItemsSource, you'll have to implement INotifyCollectionChanged on LotsOfThings, which gets to be a real hassle to rewrite all that by hand, and I'm not sure what it buys you. You could just make LotsOfThings a subclass of ObservableCollection<Thing> -- that starts you off with a complete and bulletproof INotifyCollectionChanged implementation, for free.
Ed Plunkett put me on the right path but the answer was a little more complicated so I'm laying out what I have learned in this answer.
First, I could have used ObservableCollection<T> - Ed is right. But I would have lost some of the IList<T> features I wanted. Besides I was trying to follow the practice in XAML Deep Dive ... (min 40-49) and they did not use ObservableCollection<T>.
Turns out I had mistakenly used INotifyPropertyChanged instead of INotifyCollectionChanged. The second interface has a slightly more complicated handler documented in the answer to this Stackoverflow question about calling OnCollectionChanged.
My research before asking this question found a bunch of ways to also get a null event handler. One was to call the handler with a misspelled property name (e.g. OnPropertyChanged("thing") when you should use OnPropertyChanged("Thing") because that is what the property is actually called - assuming you are dealing with properties and not collections. Another way to get a null event handler was to not bind the right object to the right content or container control. Here, take a look at "stack overflow C# why is my handler null".
And to finally put a stake in the heart of this problem I did a little research in the direction of Ed's hint that I become more familiar with the difference between List<T>, ObservableCollection<T> and INotifyPropertyChanged and found that excellent page.
I hope that helps. And thanks Ed; all my up-votes to you.
P.S. I have updated the repository of my test code to have the fix and git tag-ged the original version as broken and the fixed version as fixed.
I am attempting to write a multilingual application in Silverlight 4.0 and I at the point where I can start replacing my static text with dynamic text from a SampleData xaml file. Here is what I have:
My Database
<SampleData:something xmlns:SampleData="clr-namespace:Expression.Blend.SampleData.MyDatabase" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<SampleData:something.mysystemCollection>
<SampleData:mysystem ID="1" English="Menu" German="Menü" French="Menu" Spanish="Menú" Swedish="Meny" Italian="Menu" Dutch="Menu" />
</SampleData:something.mysystemCollection>
</SampleData:something>
My UserControl
<UserControl
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" mc:Ignorable="d"
x:Class="Something.MyUC" d:DesignWidth="1000" d:DesignHeight="600">
<Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource MyDatabase}}">
<Grid Height="50" Margin="8,20,8,0" VerticalAlignment="Top" d:DataContext="{Binding mysystemCollection[1]}" x:Name="gTitle">
<TextBlock x:Name="Title" Text="{Binding English}" TextWrapping="Wrap" Foreground="#FF00A33D" TextAlignment="Center" FontSize="22"/>
</Grid>
</Grid>
</UserControl>
As you can see, I have 7 languages that I want to deal with. Right now this loads the English version of my text just fine. I have spent the better part of today trying to figure out how to change the binding in my code to swap this out when I needed (lets say when I change the language via drop down).
It sounds like you're looking for code like this:
Title.SetBinding(TextProperty, new Binding { Path = new PropertyPath(language) });
All it does is create a new Binding for the language you requested and use it to replace the old binding for the Title's Text property.
You are going about this the wrong way. Best practice for localization in Silverlight is to use resource files holding the translated keywords. Here is some more info about this:
http://msdn.microsoft.com/en-us/library/cc838238%28VS.95%29.aspx
EDIT:
Here is an example where I use a helper class to hold the translated strings. These translations could then be loaded from just about anywhere. Static resource files, xml, database or whatever. I made this in a hurry, so it is not very stable. And it only switches between english and swedish.
XAML:
<UserControl x:Class="SilverlightApplication13.MainPage"
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:SilverlightApplication13"
mc:Ignorable="d"
d:DesignWidth="640"
d:DesignHeight="480">
<UserControl.Resources>
<local:TranslationHelper x:Key="TranslationHelper"></local:TranslationHelper>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<StackPanel>
<TextBlock Margin="10"
Text="{Binding Home, Source={StaticResource TranslationHelper}}"></TextBlock>
<TextBlock Margin="10"
Text="{Binding Contact, Source={StaticResource TranslationHelper}}"></TextBlock>
<TextBlock Margin="10"
Text="{Binding Links, Source={StaticResource TranslationHelper}}"></TextBlock>
<Button Content="English"
HorizontalAlignment="Left"
Click="BtnEnglish_Click"
Margin="10"></Button>
<Button Content="Swedish"
HorizontalAlignment="Left"
Click="BtnSwedish_Click"
Margin="10"></Button>
</StackPanel>
</Grid>
</UserControl>
Code-behind + TranslationHelper class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.ComponentModel;
namespace SilverlightApplication13
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
//Default
(this.Resources["TranslationHelper"] as TranslationHelper).SetLanguage("en-US");
}
private void BtnEnglish_Click(object sender, RoutedEventArgs e)
{
(this.Resources["TranslationHelper"] as TranslationHelper).SetLanguage("en-US");
}
private void BtnSwedish_Click(object sender, RoutedEventArgs e)
{
(this.Resources["TranslationHelper"] as TranslationHelper).SetLanguage("sv-SE");
}
}
public class TranslationHelper : INotifyPropertyChanged
{
private string _Contact;
/// <summary>
/// Contact Property
/// </summary>
public string Contact
{
get { return _Contact; }
set
{
_Contact = value;
OnPropertyChanged("Contact");
}
}
private string _Links;
/// <summary>
/// Links Property
/// </summary>
public string Links
{
get { return _Links; }
set
{
_Links = value;
OnPropertyChanged("Links");
}
}
private string _Home;
/// <summary>
/// Home Property
/// </summary>
public string Home
{
get { return _Home; }
set
{
_Home = value;
OnPropertyChanged("Home");
}
}
public TranslationHelper()
{
//Default
SetLanguage("en-US");
}
public void SetLanguage(string cultureName)
{
//Hard coded values, need to be loaded from db or elsewhere
switch (cultureName)
{
case "sv-SE":
Contact = "Kontakt";
Links = "Länkar";
Home = "Hem";
break;
case "en-US":
Contact = "Contact";
Links = "Links";
Home = "Home";
break;
default:
break;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}