canton7 / Stylet

A very lightweight but powerful ViewModel-First MVVM framework for WPF for .NET Framework and .NET Core, inspired by Caliburn.Micro.
MIT License
988 stars 143 forks source link

Proper way for creating custom UserControls with Stylet #125

Closed Eagle2 closed 4 years ago

Eagle2 commented 4 years ago

Hello, First of all thank you for creating Stylet. It really helped me to understand a lot about mvvm.

So far I managed to work smooth with my views and viewmodels in application, but now i stuck while creating reusable ListBox with some custom properties like "ListName" and different ItemTemplate depending on collection of objects i provide in MyCustomItemsSource property.

I can't figure out how can i use attached properties or dependency properties inside my UserControl while i deleted all code behind. Ideally i want to use localized string like: <UserControls:EditableListBoxWithHeader ListName="{Translate:Loc MyLocalizedString}" s:View.Model="{Binding MyListOfObjects}" /> and be able to define custom ItemTemplate for ListBox inside EditableListBoxWithHeader user control.

There comes simplified user control i want to create: `public partial class EditableListBoxWithHeader : UserControl { public string ListName { get { return (string)GetValue(ListNameProperty); } set { SetValue(ListNameProperty, value); } }

    public static DependencyProperty ListNameProperty =
        DependencyProperty.Register("ListName", typeof(string), typeof(EditableListBoxWithHeader), new PropertyMetadata("default-ListName-value"));

    public EditableListBoxWithHeader()
    {

    }
}`

and xaml for it, but it for sure does not work .

`<UserControl x:Class="MyApp.Components.Library.UserControls.Views.EditableListBoxWithHeader" 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:s="https://github.com/canton7/Stylet" d:DesignWidth="200" d:DesignHeight="400" mc:Ignorable="d">

`

I will maybe have some more questions but I should move forward after passing some dependency or attached properties and list of objects to ListBox inside UserControl.

canton7 commented 4 years ago

I can't figure out how can i use attached properties or dependency properties inside my UserControl while i deleted all code behind.

For UserControls, I wouldn't delete the codebehind. UserControls aren't part of normal MVVM: they're pretty low-level, they don't have a ViewModel, and they often have custom stuff in the codebehind.