I'm currently dabbling in WPF with C# the teachers i have for it know how to use windows forms, but not much about WPF. I can see that it's a bit of a different way to work with the GUI, but it seems solid.
While following a small crash course, I was trying to add a class as the datacontext for the MainWindow by using the XAML, but i seem unable to do it correctly. I've seen quite a few posts about it on here, but none of the things seem quite the same as what I'm experiencing. Here's My XAML
<Window x:Class="WPFTest.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:WPFTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:AddressBookViewModel />
</Window.DataContext>
<Grid x:Name="WPFTest">
<Button x:Name="btnNewContact" Content="Create a New Contact" HorizontalAlignment="Left" Margin="10,273,0,0" VerticalAlignment="Top" Width="209"/>
<Label x:Name="lblName" Content="Name:" HorizontalAlignment="Left" Margin="259,129,0,0" VerticalAlignment="Top"/>
<Label x:Name="lblEmail" Content="E-Mail:" HorizontalAlignment="Left" Margin="259,160,0,0" VerticalAlignment="Top"/>
<Label x:Name="lblPhone" Content="Phone:" HorizontalAlignment="Left" Margin="259,191,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="txtName" HorizontalAlignment="Left" Height="23" Margin="327,133,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtEmail" HorizontalAlignment="Left" Height="23" Margin="327,164,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtPhone" HorizontalAlignment="Left" Height="23" Margin="327,195,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<ListBox x:Name="lbxContacts" HorizontalAlignment="Left" Height="204" Margin="10,53,0,0" VerticalAlignment="Top" Width="209"/>
</Grid>
And my Class which i would like to use as a ViewModel:
namespace WPFTest
{
public class AddressBookViewModel
{
public AddressBookViewModel()
{
}
protected List<Contact> contacts = new List<Contact>();
protected Contact selectedContact = null;
public List<Contact> Contacts
{
get
{
return contacts;
}
set
{
contacts = value;
}
}
public Contact SelectedContact
{
get
{
return selectedContact;
}
set
{
selectedContact = value;
}
}
}
}
This, however, just gives me an error:
The name "AddressBookViewModel" does not exist in the namespace "clr-namespace:WPFTest".
I Simply do not comprehend what is going wrong. It seems to me that AddressBookViewModel does indeed very much exist in this namespace, but Visual Studio clearly disagrees.
Can someone please explain to me the problem?
I understand that i can bind the Datacontext in the code behind, however, i can see the value in being able to do it in the XAML