I want my user control to display data when I am viewing it in the WPF designer in Visual Studio.
The ViewModel does not have a default constructor, so I wrote my own static TestData
class to construct the model and all of its dependencies.
public static class TestData
{
public static ELabelViewModel ELabelViewModel
{
get
{
return new ELabelViewModel
(
new ControlPanelGridLine(TestData.ELabel),
new SerialPortFactoryImpl(),
new Repository(),
new PriceLabelGenerator(TestData.IPriceLabelViewModelFactory)
);
}
}
// Other static getter methods
This all compiles with no problems. However, problems start when I add this in the XAML:
d:DataContext="{x:Static local:TestData.ELabelViewModel}"
The XAML editor puts a curly blue line under my d:DataContext
attribute, and in the error list I see:
Error 7 Method not found: 'Void ELabel.Manager.ViewModels.ELabelViewModel..ctor(ELabel.Manager.ViewModels.ControlPanelGridLine, ELabel.Control.ISerialPortFactory, ELabel.Data.IRepository, ELabel.ImageGeneration.IPriceLabelGenerator)'.
My interpretation of this is that it is finding the TestData
class, and also finding the TestData.ELabelViewModel
property. It just cannot resolve the constructor that is being called inside the getter.
Why can it not find the ELabelViewModel
constructor? To confirm my code was OK, I made this test view model the actual data context by using DataContext=
instead of d:DataContext=
. In this case I opened the application and confirmed that, at runtime, all works as expected: TestData.ELabelViewModel
was invoked, the code insider the getter function ran, and it used this view model. It's just the designer that is failing to run the code.
The ELabelViewModel
class is in a separate assembly called ELabel.Manager.ViewModels
. Is the editor failing to fully load this assembly?
Later Edit
I tried moving this TestData
class to the ELabel.Manager.ViewModels
assembly (the same assembly that the constructor resides in). Sure enough, it now works fine, and I can see test data when viewing the control in the editor. Curious.
I've double-checked that the ELabelViewModel
class and the constructor are public (Which of course it is, otherwise I never would have been able to build the application).
I implement all my viewmodel classes like this:
<UserControl x:Class="MyApp.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:vm="clr-namespace:MyApp.ViewModel"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Height="607" Width="616">
<UserControl.DataContext>
<vm:TestData/>
</UserControl.DataContext>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With