Declaring Design-Time ViewModel for Avalonia Window - c#

I'm looking for the right approach to declare design-time ViewModel for an Avalonia window.
Some samples suggest
d:DataContext="{d:DesignInstance viewModels:LoginViewModel, IsDesignTimeCreatable=True}"
This throws
XamlParseException at 5:5: Unable to resolve type DesignInstance from namespace http://schemas.microsoft.com/expression/blend/2008
Default Avalonia MVVM template suggests
<Design.DataContext>
<vm:MainWindowViewModel/>
</Design.DataContext>
If the ViewModel takes parameters, it throws
XamlLoadException at 16:10: Unable to find public constructor for type Demo.CloseNonModalDialog:Demo.CloseNonModalDialog.CurrentTimeDialogViewModel()
I guess adding a default parameter-less constructor is an option.
With MvvmLight/WPF, I used to reference the ViewLocator as a static resource
DataContext="{Binding Source={StaticResource Locator}, Path=MainWindow}"
That's an option, although I haven't yet found the right way to declare and reference the resource.
What is the recommended approach here? If I want to show design-time data, I'd say only the 3rd option would work. Which is not the option shown in samples.

Unable to find public constructor for type Demo.CloseNonModalDialog:Demo.CloseNonModalDialog.CurrentTimeDialogViewModel()
You can specify arguments via x:Arguments XAML directive, see https://learn.microsoft.com/en-us/dotnet/desktop/xaml-services/xarguments-directive
That's an option, although I haven't yet found the right way to declare and reference the resource.
I'd suggest to declare DesignData class and use x:Static, it will give you way more flexibility. e. g.
class DesignData
{
public MyViewModel MyViewModel => new MyViewModel(...);
}
d:DataContext="{x:Static local:DesignData.MyViewModel}"
View model creation would also not happen during the normal app execution unlike the StaticResource approach.

Related

XAML c# instantiating object overloaded constructor [duplicate]

While using WPF I noticed that when I add a control to a XAML file, the default constructor is called.
Is there a way to call a parameterized constructor?
.NET 4.0 brings a new feature that challenges the answer - but apparently only for UWP applications (not WPF).
x:Arguments Directive
<object ...>
<x:Arguments>
oneOrMoreObjectElements
</x:Arguments>
</object>
One of the guiding principles of XAML-friendly objects is that they should be completely usable with a default constructor, i.e., there is no behavior that is only accessible when using a non-default constructor. To fit with the declarative nature of XAML, object parameters are specified via property setters. There is also a convention that says that the order in which properties are set in XAML should not be important.
You may, however, have some special considerations that are important to your implementation but at odds with convention:
You may have one or more properties which must be set before the object can be used.
Two or more properties may be mutually exclusive with each other, e.g., it makes no sense to set both the StreamSource and UriSource of an image.
You may want to ensure that a property is only set during initialization.
One property may depend on another, which can be tricky due to the aforementioned convention of order independence when setting properties.
To make it easier to handle these cases, the ISupportInitialize interface is provided. When an object is read and created from XAML (i.e., parsed), objects implementing ISupportInitialize will be handled specially:
The default constructor will be called.
BeginInit() will be called.
Properties will be set in the order they appeared in the XAML declaration.
EndInit() is called.
By tracking calls to BeginInit() and EndInit(), you can handle whatever rules you need to impose, including the requirement that certain properties be set. This is how you should handle creation parameters; not by requiring constructor arguments.
Note that ISupportInitializeNotification is also provided, which extends the above interface by adding an IsInitialized property and Initialized event. I recommend using the extended version.
No. Not from XAML [when using WPF].
Yes, you can do it by the ObjectDataProvider. It allows you to call non-default constructor, for example:
<Grid>
<Grid.Resources>
<ObjectDataProvider x:Key="myDataSource"
ObjectType="{x:Type local:Person}">
<ObjectDataProvider.ConstructorParameters>
<system:String>Joe</system:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
</Grid.Resources>
<Label Content="{Binding Source={StaticResource myDataSource}, Path=Name}"></Label>
</Grid>
assuming that Person is
public class Person
{
public Person(string Name)
{
this.Name = Name;
}
public string Name { get; set; }
}
Unfortunately, you cannot bind the ConstructorParameters. See some workaround here.

Understanding XAML syntax

I have a Theme attribute that I can load like this:
<xcad:DockingManager>
<xcad:DockingManager.Theme>
<xcad:AeroTheme>
</xcad:AeroTheme>
</xcad:DockingManager.Theme>
AeroTheme is a class. How can I achieve the same result via attributes?
<xcad:DockingManager Theme="What should I write here?">
You need an instance of that theme, which you can provide as a static resource. For example if the parent control is a grid:
<Grid.Resources>
<xcad:AeroTheme x:Key="myTheme"/>
</Grid.Resources>
<xcad:DockingManager Theme="{StaticResource myTheme}">
Generally, it's impossible to set a property of a complex type (a class for example) via attribute in xaml without declaring this object in Xaml explicitelly. When XAML is parsed the actual object tree is being constructed. Xaml give you the possibility to use attributes in much more extended way than common XML. In particular, you can write something like this:
<Grid Backgroud="Red"/>
In compile time, Red is nothing more than string value. However WPF does the magic behind the scene. The magic is that WPF read the type of property via reflection (in this example Background property type is a Brush), it finds TypeConverterAttribute on Brush class (once again via reflection) and use appropriate classes derieving from TypeConverter to make a conversion from string. In this example WPF would use BrushConverter class (located in PresentationCore assmebly) and call ConvertFrom method to get actual Brush object to set the Background property.
Of course using this way is not straightforward. In your example, to make it possible you should have the following conditions satisfied:
A class AeroTheme should be marked with TypeConverterAttribute
The type specified in the attribute is an instance of TypeConverter class.
In your TypeConverter you have the logic for converting from string to AeroTheme object (via implementing method from TypeConverter).
Code example:
[TypeConverter(typeof(AeroThemeConverter)]
public class AeroTheme
{
...
}
public class AeroThemeConverter : TypeConverter
{
//implementation of convertion here
}
In this way if you would have in XAML:
<xcad:DockingManager Theme="Aero">
WPF does the magic and set your Theme property using the conversion written in AeroThemeConverter.
This is of course neighter full nor work example, but it shows the idea. To get more information about this see the MSDN documentation:
https://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter(v=vs.110).aspx
So the only way to set a property via attribute (without declaring it in XAML) is to make use of the described mechanism.
Another way is to declare an object and use a MarkupExtension (StaticResource, DynamicResource, various types of Binding etc) as shown above.

Having my Viewmodel appear in namespace dropdown

I'm trying to expose the ViewModel as a static resource on the page so that it can be easily accessible by the binding.
TestViewModel.cs
namespace Test.WPFUI.Home
{
public class TestViewModel....
HelloWorldView.Xaml
xmlns:local="clr-namespace:Test.WPFUI.Home"
<UserControl.Resources>
<local:TestViewModel x:Key="mainPageViewModel" />
</UserControl.Resources>
TestViewModel Can't be found. May I ask for some tips or suggestions Please.
Getting help from http://www.telerik.com/help/silverlight/gridview-troubleshooting-blank-cells.html
public class LoanViewModel : ScreenViewModelBase<LoanViewModel>, IRecord, INotifyPropertyChanged
{
public LoanViewModel(IEventAggregator events) .............
It sounds like your initial problem was not having the full xmlns definition. You usually need both the namespace and assembly.
The easiest way to get it right, in my experience, is to let intellisense do it for you. Just start typing the namespace you want, and as long as its in a referenced project, there will be an autocomplete option.
Your second problem is due to not having a default constructor. You wrote this:
<local:TestViewModel x:Key="mainPageViewModel" />
Which will invoke the default constructor. However, you define a constructor here:
public LoanViewModel(IEventAggregator events) .............
Which removes the provided (paramaterless) default constructor. I'm going to take a wild guess and say that creating the correct IEventAggregator is not simple or desired from XAML, so I see two choices:
You didn't really need that parameter in the constructor. Simply add a default constructor to your view model and you are good to go!
You really need that parameter, so instantiating from XAML just isn't a good idea. Pass in your view model from somewhere else on the view's constructor.
If you feel like you can instantiate the correct object from XAML, use this post to invoke the paramaterized constructor: Calling a parameterized constructor from XAML
In my opinion, putting truly regular classes into XAML is not a good pattern to follow, so I wouldn't. By regular, I mean not related at all to the view.

Where does the code for WPF a window/usercontrol resource go?

I'm trying to follow this tutorial, but I'm not clear on where the code for the EnumMatchToBooleanConverter class is supposed to go. I assumed that it would go in the code-behind file (i.e. view.xaml.cs), but then I get an error along the lines of The type EnumMatchToBooleanConverter was not found when I try declaring the resource in the XAML.
In general, a small WPF project should have the following approximate folder structure:
ProjectName
Converters
DataAccess
DataTypes
Images
ViewModels
Views
Converters is the folder where you should store your Converter classes. After developing WPF for a while, you'll find that your collection of Converter classes will increase in size. Each of these folders contain classes that we map to related namespaces. In the case of the Converter classes, it would typically be like this:
namespace ProjectName.Converters
{
[ValueConversion(typeof(bool), typeof(Brush))]
public class BoolToBrushConverter : IValueConverter
{
...
}
}
For the DataTypes classes, you'd use something like:
namespace ProjectName.DataTypes
{
public class SomeDataType
{
...
}
}
As #LordTakkera correctly mentioned, you'd then need to reference these classes in XAML by defining a XAML namespace like so:
xmlns:Converters="clr-namespace:ProjectName.Converters"
Then you could define the Converter in the Resources section like this:
<Converters:BoolToBrushConverter x:Key="BoolToBrushConverter" />
See the Data Conversion section of the Data Binding Overview page on MSDN for more information. The IValueConverter interface page on MSDN is another useful resource.
EnumMatchToBooleanConverter in this case is its own class. You should be able to declare it in a existing code behind, but I would stick it into its own file just to be sure.
Visual Studio can be dumb when finding resources, so you should rebuild the project in case errors are still shown.
Converters (like all other classes) belong in their own file.
Then, you just need to include the namespace in your XAML:
xmlns:local="clr-namespace:MyNamespace"
Also, try rebuilding/running the app as the XAML "intellisense" often won't update what is in the namespaces until a build has taken place.

Is it okay to declare the view model as a static resource in a view?

When writing a MVVM WPF app, there's always a point where the view model has to be set to as the data context of the view. For me, usually that's in code. But I realized that if I declare the view model as a static resource inside the xaml and set the binding there, I don't need to do it in code anymore. This means I don't have to coordinate the view and the viewmodel in a third class somewhere, like in the App.
Is it acceptable to do this?
Thanks!
I'd say so. It sort of implies specific knowledge of the ViewModel from the View, but you have to set it somehow and I like the codebehindless approach here.
If you are using dependency injection this would not be appropriate, but if you aren't I'd stick with this approach.
Acceptable, yes, but if you are using PRISM, or DI of any sort, then it would make more sense to resolve it from the container and then set the datacontext either in code, or using a markup extension, depending on your exact solution.
If you want to use Dependency Injection (DI) in the View-First approach try ViewModel locator pattern:
public static class ViewModelLocator
{
public static MainWindowViewModel MainWindowViewModel
{
get
{
return ObjectFactory.GetInstance<MainWindowViewModel>();
}
}
};
and WPF code:
<Window
...
DataContext="{x:Static Services:ViewModelLocator.MainWindowViewModel}"
>

Categories