I was testing something out on the Windows Phone 7 platform and, when tried to add a button Click event, Visual Studio 2010 gave me the following error:
To generate an event handler the class 'MainPage', specified by the x:Class or x:Subclass attribute, must be the first class in the file. Move the class code so that it is the first class in the file and try again.
This is what my MainPage.xaml.cs file looked like:
public class TestItem
{
public string Name { get; set; }
public int Count { get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
List<TestItem> li = new List<TestItem>();
TestItem a = new TestItem { Name = "First name", Count = 1 };
TestItem b = new TestItem { Name = "Second name", Count = 2 };
TestItem c = new TestItem { Name = "Third name", Count = 3 };
listBox1.DataContext = li;
}
}
Then I realized that I put together a dummy class to test binding on a ListBox and put it on the top of the document. Once I moved the TestItem class definition down, the page compiled and I was able to add events from the XAML page. Here is what the working code looks like:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
List<TestItem> li = new List<TestItem>();
TestItem a = new TestItem { Name = "First name", Count = 1 };
TestItem b = new TestItem { Name = "Second name", Count = 2 };
TestItem c = new TestItem { Name = "Third name", Count = 3 };
listBox1.DataContext = li;
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
}
}
public class TestItem
{
public string Name { get; set; }
public int Count { get; set; }
}
1 comment:
Yip- did the same thing. Thanks for documenting the fix. :)
Post a Comment