WPF MVVM ErrorCode: CS1061 - c#

- the red markups are for Inputs(xAxis and yAxis)
- after i press the button (Calculate), the inputs should be calculated.
- then outputed at the blue markup(texbox called Output)
After i made some kata with element binding, i just wanted to
start MVVM property binding.
For some reason i get a ErrorCode: CS1061
Error CS1061 MainWindow does not contain a definition for
CalculateClick and no extension method CalculateClick accepting a
first argument of type MainWindow could be found (are you missing a
using directive or an assembly reference?)
the weird part of this is when i use the resharper eventhandler on my MainWindow.xml at my button it creates a event in my MainWindow.cs.
But it didnt before. the events were autocreated in my ViewModel.cs
im not sure what causes this error
ty in advance when somone could help me, i have already been sitting on this kata for more then 8 hours.
Heres my MainWindow.xml:
<Window x:Class="Coordinates.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:Coordinates"
mc:Ignorable="d"
Title="MainWindow" Height="250" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Insert X-Coordiante"/>
<Label Grid.Row="0" Grid.Column="1" Content="Insert Y-Coordinate"/>
<TextBox Grid.Row="1" Grid.Column="0" Name="TxtXaxis" Text="{Binding Xaxis}"/>
<TextBox Grid.Row="1" Grid.Column="1" Name="TxtYaxis" Text="{Binding Xaxis}"/>
<TextBox Grid.Row="2" Grid.Column="0" Text="{Binding Output}"/>
<Button Grid.Row="2" Grid.Column="1" Name="Calculate" Click="CalculateClick">Calculate</Button>
</Grid>
This is my MainWinow.xml.cs:
using System.Windows;
namespace Coordinates
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.InitializeComponent();
this.DataContext = new ViewModel();
}
}
}
This is my ViewModel.cs:
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace Coordinates
{
public class ViewModel : INotifyPropertyChanged
{
#region Inputs
private double _xaxis;
public double Xaxis
{
get => this._xaxis;
set
{
if (value == this._xaxis)
{
return;
}
this._xaxis = value;
this.OnPropertyChanged();
}
}
private double _yaxis;
public double Yaxis
{
get => this._yaxis;
set
{
if (value == this._yaxis)
{
return;
}
this._yaxis = value;
this.OnPropertyChanged();
}
}
#endregion
public void CalculateClick(object sender, RoutedEventArgs e)
{
Output = Math.Sqrt(Math.Pow(Xaxis,2)+Math.Pow(Yaxis,2));
}
private double _output;
public double Output
{
get => this._output;
set
{
if (value == this._output)
{
return;
}
this._output = value;
this.OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
EDIT: this was missing in CalculateClick in my viewmodel:
Output = Math.Sqrt(Math.Pow(Xaxis,2)+Math.Pow(Yaxis,2));

You are using a CalculateClick as Eventhandler for the Click Event of the Button.
Per Default, WPF looks in the Code Behind (MainWindow.cs) for the Eventhandler, which is not there.
Since you are already initializing your DataContext within the Code Behind. Make your ViewModel a private member of your MainWindow.
Create an event handler in the MainWindow Code Behind and call your event handler in the ViewModel from there.
public partial class MainWindow : Window
{
private _viewModel = new ViewModel();
public MainWindow()
{
InitializeComponent();
this.InitializeComponent();
this.DataContext = _viewModel;
}
}
public void CalculateClick(object sender, RoutedEventArgs e)
{
_viewModel.CalculateClick(Sender, e);
}
You might also want to look into Commands, which can be created directly inside of the ViewModel and then be bound to. There is an ActionCommand or GenericCommand, which take an Action or Action<T> and are pretty easy to use.

Related

MVVM Hierarchical Navigation tutorial StackOverFlow exception

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.

C# WPF Update Textbox on Property change

I got an Problem with updating the text in a Textbox. I got this MainWindow:
<Window x:Class="TestDatabinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10,10,10,10"/>
<Button Grid.Row="1" Content="Click me" Margin="10,10,10,10" Click="Button_Click"></Button>
<Button Grid.Row="2" x:Name="a1" Content="ShowText" Margin="10,10,10,10" Click="a1_Click" ></Button>
</Grid>
Now the cs-file for this MainWindow looks like:
using System.Windows;
namespace TestDatabinding
{
public partial class MainWindow : Window
{
MainWindowViewModel mwvm;
public MainWindow()
{
InitializeComponent();
mwvm = new MainWindowViewModel();
this.DataContext = mwvm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
mwvm.ChangeText();
this.DataContext = mwvm;
}
private void a1_Click(object sender, RoutedEventArgs e)
{
mwvm.showText();
}
}
}
And last but not least the ViewModel Class:
using System.ComponentModel;
using System.Windows;
namespace TestDatabinding
{
class MainWindowViewModel
{
public event PropertyChangedEventHandler PropertyChanged;
private string text;
public string Text
{
get { return this.text; }
set
{
this.text = value;
OnPropertyChanged("Text");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public void ChangeText()
{
this.Text = "Hey paadddyy";
}
public void showText()
{
MessageBox.Show(Text);
}
}
}
I didn´t implement ICommands, because this is a simple test.
Now the Button's work correctly but the Textbox Text didn´t get updated.
Any suggestions what i can do? I only want to display "Hey paadddyy" when I click the first Button. After I press the second Button and then the first the MessageBox shows "Hey paadddyy" but the Textbox text didn´t get updated :(
Thank you for every hint ;)
Your MainWindowViewModel does not implement INotifyPropertyChanged. It needs to look like that:
class MainWindowViewModel: INotifyPropertyChanged
you define the event but does not implement the interface
It need to implement INotifyPropertyChanged
I suggested that if you want to do something with Notify Property. Another easy way is to apply Caliburn.Micro Framework to your project.
Follow this link.

Databinding and then calling from another class in WPF

My purpose is to add a textblock to my main UI window, of which text will be updated if needed. For that, in my UIWindow xaml I did like this:
<Window x:Class="UIDesigner.UIWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:UIDesigner"
xmlns:c="clr-namespace:UIDesigner.Controls"
WindowStartupLocation="CenterScreen"
WindowState="Maximized"
WindowStyle="SingleBorderWindow"
Title="GUI"
Height="1000" Width="1400"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Icon="Resources/Images/Logo.png"
>
<Grid Margin="0">
<Grid Grid.Row="1" Margin="0,10,0,0">
<GroupBox Header="Console" Grid.Column="1" Margin="0,590,0,0" HorizontalAlignment="Stretch" x:Name="consoleWindow" IsEnabled="True" VerticalAlignment="Stretch"
>
<TextBlock x:Name="myConsoleWindowTextBlock" Text="{Binding Path=consoleText}"/>
</GroupBox>
</Grid>
</Grid>
</Window>
This is the code behind:
using System.Windows;
using System.Runtime.CompilerServices;
using System.ComponentModel;
namespace UIDesigner
{
public partial class UIWindow : Window
{
public UIWindow()
{
InitializeComponent();
}
private string _consoleText;
public string consoleText
{
get{ return _consoleText;}
set
{
_consoleText = value;
NotifyPropertyChanged("consoleText");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
}
Then in my main class, I call this UIWindow like this:
namespace UIDesigner
{
public partial class Main : Window
{
public Main()
{
InitializeComponent();
}
private void LoginButton_Click_1(object sender, RoutedEventArgs e)
{
var myUIWindow = new UIWindow();
myUIWindow.PropertyChanged += new PropertyChangedEventHandler(UIWindow_PropertyChanged);
myUIWindow.consoleText = "Hello User!";
myUIWindow.ShowDialog();
this.Close();
}
private void LoginButton_MouseEnter_1(object sender, MouseEventArgs e)
{
}
static void UIWindow_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
MessageBox.Show("Something Changed!");
MessageBox.Show(e.PropertyName);
}
}
}
Now I have two problems here:
First, when my UI window starts, I indeed received two message boxes, saying "something changed" followed by "consoleText". So that means the consoleText is changed successfully. But after my UIWindow shows up, the textblock is empty, I cannot see "Hello User!" there. Seems like Text="{Binding Path=consoleText} part is not working correctly in my xaml file.
Second and most importantly, I want to change the consoleText in another different class, namely in DesignerCanvas.Commands.cs. For that I couldn't figure out any solution. I want something like this in my DesignerCanvas.Commands.cs:
namespace UIDesigner
{
public partial class DesignerCanvas
{
private void changeConsoleOutput(string updatedConsoleText)
{
myUIWindow.consoleText = updatedConsoleText; //obviously, this is not working
}
}
}
Any kind of suggestion will be much appreciated.
1.First of two set the value in UI just add below one line
in constructor of UIWindow class
this.DataContext=this;
//because only specifying property consoletext, it will not able to know where to find consoletext.
2.u can find that UIwindow in App.Current.Windows and cast it to UIWindow type and then can
access the property.
foreach(Window win in App.Current.Windows)
{
if (win as UIWindow != null)
{
(win as UIWindow).consoletext = updatedConsoleText;
}
}
For second problem
Change
<TextBlock x:Name="myConsoleWindowTextBlock" Text="{Binding Path=consoleText}"/
To
<TextBlock x:Name="myConsoleWindowTextBlock" Text="{Binding Path=.}"/
and
in UIWindow constructor set
myConsoleWindowTextBlock.Datacontext=consoleText;

Freezing main window after adding some items from childwindow

I am working on Silverlight 4 with mvvm and WCF services.
Whenever I am adding items from child window to main window. But at the same time main window automatically going to disabling mode. I think main window automatically freezes.
ChildWindow ViewModel
public class AddFormFieldInformationViewModel : ViewModelBase
{
private FieldInformationViewModel _FieldInformationViewModel;
public FieldInformationViewModel FieldInformationViewModel
{
get { return _FieldInformationViewModel; }
set
{
_FieldInformationViewModel = value;
RaisePropertyChanged("FieldInformationViewModel");
}
}
public void MoveSave(object obj)
{ this.FieldInformationViewModel.SelectedFormFields = FieldInformationModel;
ResultHandler(true);
}
public Action ResultHandler { get; set; }
}
ChildWindow .xaml.cs file
public partial class AddExistingFormFieldCategoryView : ChildWindow
{
private AddFormFieldInformationViewModel vm;
public AddExistingFormFieldCategoryView()
{
InitializeComponent();
vm = new AddFormFieldInformationViewModel();
this.DataContext = vm;
vm.ResultHandler = result => { if (result) { Close(); } };
}
}
Main Window ViewModel
public class FieldInformationViewModel : ViewModelBase
{ private void executeOpenChildWindow(object parameter)
{
AddExistingFormFieldCategoryView cw = new AddExistingFormFieldCategoryView();
((AddFormFieldInformationViewModel)cw.DataContext).FieldInformationViewModel = this;
cw.Show();
}
}
After adding items from child window into main window, sometimes my main window is automatically freezing.
Hi this is a bug you are experiencing see the sample below. I the same issue and you have to manually enable the display of the main page:
private static void ShowError(string message, string details)
{
ErrorWindow error = new ErrorWindow(message, details);
error.Closed += new EventHandler(error_Closed);
error.Show();
}
static void error_Closed(object sender, EventArgs e)
{
Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, true);
}
You can subclass the ChildWindow and explicitly set the RootVisual to enabled. Source
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace DST_Common_Silverlight_Controls
{
/// <summary>
/// Bug in ChildWindow sometimes leaves app disabled.
/// </summary>
public class ChildWindowEx : ChildWindow
{
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, true);
}
}
}
Then just use the new type instead of ChildWindow in xaml like this:
<slcommon:ChildWindowEx
x:Class="DST.AvSyncMonitor.Silverlight.Gui.ErrorWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:slcommon="clr-namespace:DST_Common_Silverlight_Controls;assembly=DST.Common.Silverlight.Controls"
xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
Title="Error">
<Grid x:Name="LayoutRoot" Width="540">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock x:Name="IntroductoryText" Grid.Row="0" Margin="0"
Text="An unknown error was encountered. Please contact your administrator for more information."/>
<StackPanel x:Name="ContentStackPanel" Grid.Row="2" Margin="0,6,0,0">
<TextBlock x:Name="LabelText" TextWrapping="Wrap" Margin="0,0,0,2"
Text="Error details"/>
<TextBox x:Name="ErrorTextBox" Height="90" TextWrapping="Wrap" IsReadOnly="True"
VerticalScrollBarVisibility="Auto"/>
</StackPanel>
<Button x:Name="OKButton" Grid.Row="3" Click="OKButton_Click"
Width="75" Height="23" HorizontalAlignment="Right" Margin="0,10,0,0"
TabIndex="0" Content="OK"/>
</Grid>
</slcommon:ChildWindowEx>

WPF Binding ListBox Master/Detail

I can get this working with an XmlDataSource but not with my own classes. All I want to do is bind the listbox to my collection instance and then link the textbox to the listbox so I can edit the person's name (two-way). I've deliberately kept this as simple as possible in the hope that somebody can fill in the blanks.
XAML:
<Window x:Class="WpfListTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfListTest"
Title="Window1" Height="300" Width="600">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="3"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<DockPanel Grid.Column="0">
<ListBox />
</DockPanel>
<DockPanel Grid.Column="2">
<StackPanel>
<Label>Name</Label>
<TextBox />
</StackPanel>
</DockPanel>
</Grid>
</Window>
C# code behind:
namespace WpfListTest
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public People MyPeeps = new People();
public Window1()
{
InitializeComponent();
MyPeeps.Add(new Person("Fred"));
MyPeeps.Add(new Person("Jack"));
MyPeeps.Add(new Person("Jill"));
}
}
public class Person
{
public string Name { get; set; }
public Person(string newName)
{
Name = newName;
}
}
public class People : List<Person>
{
}
}
All the examples on the web seem to have what is effectively a static class returning code-defined data (like return new Person("blah blah")) rather than my own instance of a collection - in this case MyPeeps. Or maybe I'm not uttering the right search incantation.
One day I might make a sudden breakthrough of understanding this binding stuff but at the moment it's baffling me. Any help appreciated.
The correct way would be to use the MVVM pattern and create a ViewModel like so:
public class MainWindowViewModel : INotifyPropertyChanged
{
private People _myPeeps;
private Person _selectedPerson;
public event PropertyChangedEventHandler PropertyChanged;
public People MyPeeps
{
get { return _myPeeps; }
set
{
if (_myPeeps == value)
{
return;
}
_myPeeps = value;
RaisePropertyChanged("MyPeeps");
}
}
public Person SelectedPerson
{
get { return _selectedPerson; }
set
{
if (_selectedPerson == value)
{
return;
}
_selectedPerson = value;
RaisePropertyChanged("SelectedPerson");
}
}
private void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Initialize it in your View's code behind like so:
public partial class MainWindow : Window
{
private readonly MainWindowViewModel _viewModel;
public MainWindow()
{
_viewModel = new MainWindowViewModel();
_viewModel.MyPeeps = new People();
_viewModel.MyPeeps.Add(new Person("Fred"));
_viewModel.MyPeeps.Add(new Person("Jack"));
_viewModel.MyPeeps.Add(new Person("Jill"));
DataContext = _viewModel;
InitializeComponent();
}
}
And bind the data like so:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160" />
<ColumnDefinition Width="3" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<DockPanel Grid.Column="0">
<ListBox SelectedItem="{Binding SelectedPerson}"
DisplayMemberPath="Name"
ItemsSource="{Binding MyPeeps}" />
</DockPanel>
<DockPanel Grid.Column="2">
<StackPanel>
<Label>Name</Label>
<TextBox Text="{Binding SelectedPerson.Name}" />
</StackPanel>
</DockPanel>
</Grid>
</Window>
The binding will work like this:
The DataContext of the window itself is set to the ViewModel instance. Because the ListBox and the TextBox don't specify any DataContext, they inherit it from the Window. The bindings on an object always work relative to the DataContext if nothing else is being specified. That means that the TextBox binding looks for a property SelectedPerson in its DataContext (i.e., in the MainWindowViewModel) and for a Property Name in that SelectedPerson.
The basic mechanics of this sample are as follows:
The SelectedPerson property on the ViewModel is always synchronized with the SelectedItem of the ListBox and the Text property of the TextBox is always synchronized with the Name property of the SelectedPerson.
Try to inherit your People class from ObservableCollection<Person>

Categories