Giter Club home page Giter Club logo

bindables's Introduction

Roslyn source generator to create dependency and attached properties for WPF, Xamarin.Forms, and .NET MAUI

NuGet Bindables.Wpf NuGet Bindables.Forms NuGet Bindables.Forms AppVeyor

Requirements

  • Your class should be partial.
  • If you create a dependency property (WPF) or bindable property (Xamarin.Forms & .NET MAUI), your class should inherit from System.Windows.DependencyObject or Xamarin.Forms.BindableObject or Microsoft.Maui.Controls.BindableObject according to the project type. Attached properties don't have this requirement.
  • Bindables creates the static constructor for the class to initialize the dependency properties. If you have custom static constructor for a type, you can't use Bindables on it.

Example (WPF)

Check Types for Frameworks for other frameworks.

Your Code

using System.Windows;
using Bindables.Wpf;

public partial class YourClass : DependencyObject
{
    private static readonly string DefaultValue = "Test";

    [DependencyProperty(typeof(string))]
    public static readonly DependencyProperty RegularProperty;

    // You can use any visibility modifier.
    [DependencyProperty(typeof(string))]
    private static readonly DependencyPropertyKey ReadOnlyPropertyKey;

    [DependencyProperty(typeof(string), OnPropertyChanged = nameof(PropertyChangedCallback), DefaultValueField = nameof(DefaultValue), Options = FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)]
    public static readonly DependencyProperty CustomizedProperty;

    private static void PropertyChangedCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
    }
}

Generated Code

// Generated by Bindables
using System.Windows;

#nullable enable

public partial class YourClass
{
    [global::System.CodeDom.Compiler.GeneratedCode("Bindables.Wpf.WpfPropertyGenerator", "1.4.1")]
    public string? Regular
    {
        get => (string?)GetValue(RegularProperty);
        set => SetValue(RegularProperty, value);
    }

    [global::System.CodeDom.Compiler.GeneratedCode("Bindables.Wpf.WpfPropertyGenerator", "1.4.1")]
    public static readonly DependencyProperty ReadOnlyProperty;

    [global::System.CodeDom.Compiler.GeneratedCode("Bindables.Wpf.WpfPropertyGenerator", "1.4.1")]
    public string? ReadOnly
    {
        get => (string?)GetValue(ReadOnlyProperty);
        private set => SetValue(ReadOnlyPropertyKey, value);
    }

    [global::System.CodeDom.Compiler.GeneratedCode("Bindables.Wpf.WpfPropertyGenerator", "1.4.1")]
    public string? Customized
    {
        get => (string?)GetValue(CustomizedProperty);
        set => SetValue(CustomizedProperty, value);
    }

    [global::System.CodeDom.Compiler.GeneratedCode("Bindables.Wpf.WpfPropertyGenerator", "1.4.1")]
    static YourClass()
    {
        RegularProperty = DependencyProperty.Register(
            nameof(Regular),
            typeof(string),
            typeof(YourClass),
            new FrameworkPropertyMetadata());

        ReadOnlyPropertyKey = DependencyProperty.RegisterReadOnly(
            nameof(ReadOnly),
            typeof(string),
            typeof(YourClass),
            new FrameworkPropertyMetadata());

        ReadOnlyProperty = ReadOnlyPropertyKey.DependencyProperty;

        CustomizedProperty = DependencyProperty.Register(
            nameof(Customized),
            typeof(string),
            typeof(YourClass),
            new FrameworkPropertyMetadata(DefaultValue, (FrameworkPropertyMetadataOptions)256, PropertyChangedCallback));
    }
}

Options

You can pass following options:

Option Description
OnPropertyChanged Name of the method that will be called when the property is changed.
OnCoerceValue (WPF) Name of the method that will be called when the property is re-evaluated/coerced.
DefaultValueField Name of the static field that will provide the default value for the property.
Options (WPF) Pass System.Windows.FrameworkPropertyMetadataOptions to the dependency property.
BindingMode (Xamarin.Forms) Pass Xamarin.Forms.BindingMode to the dependency property.
BindingMode (.NET MAUI) Pass Microsoft.Maui.Controls.BindingMode to the dependency property.

Signature of OnPropertyChanged method should be:

Project Type Signature
WPF static void MethodName(DependencyObject obj, DependencyPropertyChangedEventArgs args)
Xamarin.Forms & .NET MAUI static void MethodName(BindableObject obj, object oldValue, object newValue)

Signature of OnCoerceValue method should be:

Project Type Signature
WPF static object MethodName(DependencyObject obj, object value)
Xamarin.Forms & .NET MAUI static object MethodName(BindableObject obj, object value)

Types for Frameworks

Project Type Dependency Property Type Access Type Property Suffix Field Type Attribute Type
WPF Dependency Property Read/Write Property DependencyProperty Bindables.Wpf.DependencyPropertyAttribute
WPF Dependency Property Read Only PropertyKey DependencyPropertyKey Bindables.Wpf.DependencyPropertyAttribute
WPF Attached Property Read/Write Property DependencyProperty Bindables.Wpf.AttachedPropertyAttribute
WPF Attached Property Read Only PropertyKey DependencyPropertyKey Bindables.Wpf.AttachedPropertyAttribute
Xamarin.Forms Bindable Property Read/Write Property BindableProperty Bindables.Forms.BindablePropertyAttribute
Xamarin.Forms Bindable Property Read Only PropertyKey BindablePropertyKey Bindables.Forms.BindablePropertyAttribute
Xamarin.Forms Attached Property Read/Write Property BindableProperty Bindables.Forms.AttachedPropertyAttribute
Xamarin.Forms Attached Property Read Only PropertyKey BindablePropertyKey Bindables.Forms.AttachedPropertyAttribute
.NET MAUI Bindable Property Read/Write Property BindableProperty Bindables.Maui.BindablePropertyAttribute
.NET MAUI Bindable Property Read Only PropertyKey BindablePropertyKey Bindables.Maui.BindablePropertyAttribute
.NET MAUI Attached Property Read/Write Property BindableProperty Bindables.Maui.AttachedPropertyAttribute
.NET MAUI Attached Property Read Only PropertyKey BindablePropertyKey Bindables.Maui.AttachedPropertyAttribute

bindables's People

Contributors

nextra avatar notanaverageman avatar simoncropp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

bindables's Issues

Unable to build with dotnet 5.0 CLI

We're trying to upgrade our build to use the dotnet 5.0 CLI, but our project that includes Bindables fails to build with this error.

Fody: An unhandled exception occurred:
Exception:
Could not find file 'C:\Users\username\.nuget\packages\bindables.fody\6.0.0\Bindables.Fody.dll'.
Type:
System.IO.FileNotFoundException
StackTrace:
   at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
   at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.File.OpenRead(String path)
   at IsolatedAssemblyLoadContext.LoadNotLocked(String assemblyPath) in C:\projects\fody\FodyCommon\IsolatedAssemblyLoadContext.cs:line 67
   at InnerWeaver.LoadFromFile(String assemblyPath) in C:\projects\fody\FodyIsolated\AssemblyLoader.cs:line 24
   at InnerWeaver.LoadWeaverAssembly(String assemblyPath) in C:\projects\fody\FodyIsolated\AssemblyLoader.cs:line 18
   at InnerWeaver.InitialiseWeaver(WeaverEntry weaverConfig) in C:\projects\fody\FodyIsolated\InnerWeaver.cs:line 157
   at InnerWeaver.InitialiseWeavers() in C:\projects\fody\FodyIsolated\InnerWeaver.cs:line 145
   at InnerWeaver.Execute() in C:\projects\fody\FodyIsolated\InnerWeaver.cs:line 106
Source:
System.Private.CoreLib
TargetSite:
Microsoft.Win32.SafeHandles.SafeFileHandle ValidateFileHandle(Microsoft.Win32.SafeHandles.SafeFileHandle)

Other weavers appear to be working fine.

Error Build with generic.xaml and CustomControl

I try to your [DependancyProperty] to create a simple ImageButton

public class ButtonImage : Button { static ButtonImage() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ButtonImage), new FrameworkPropertyMetadata(typeof(ButtonImage))); } [DependencyProperty] public ImageSource ImageA{ get; set; } }

<Style TargetType="{x:Type controls:ButtonImage}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type controls:ButtonImage}"> <Grid VerticalAlignment="Center" Margin="5"> <Grid.RowDefinitions> <RowDefinition Height="45"/> <RowDefinition Height="25"/> </Grid.RowDefinitions> <Image Grid.Row="0" Source="{TemplateBinding ImageA}" /> <Label Grid.Row="1" Content="{TemplateBinding Content}" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>

But build fail, No found ImageA in the class ButtonImage

With a standard full definition of DependencyProperty , its OK

Support for coerceValueCallback

It would be great if there was support for an 'OnCoerceValue' callback similar to the already implemented OnPropertyChanged callback feature:

[DependencyProperty]
public class YourClass : DependencyObject
{
    // Dependency property with CoerceValueCallback.
    // This setting expects that a method with signature like below exists in the class.
    // static object NameOfTheMethod(DependencyObject, object)
    [DependencyProperty(OnCoerceValue = nameof(OnCoerceValue))]
    public int WithCallback { get; set; }
    
    private static object OnCoerceValue(
        DependencyObject dependencyObject,
        object baseValue)
    {
    }
    
}

Application freeze when declaring DP in class with generic

When declaring a DP using Bindables in a generic class, the application freezes.

namespace BindablesGeneric
{
    public class MyLabel : MyLabel<string>
    {
    }

    public class MyLabel<T> : Label
    {
        //This one hang the execution, need to force close Visual Studio

        [DependencyProperty]
        public object MyProperty { get; set; }



        //This one works

        //public static readonly DependencyProperty MyPropertyProperty =
        //    DependencyProperty.Register(nameof(MyProperty), typeof(object), typeof(MyLabel<T>), new PropertyMetadata(null));

        //public object MyProperty
        //{
        //    get { return (object)GetValue(MyPropertyProperty); }
        //    set { SetValue(MyPropertyProperty, value); }
        //}
    }
}

Cannot get DependencyPropertyDescriptor

I'm using Bindables.Fody 0.4.0 with Fody 2.1.2, decided to upgrade to 4.0 today.

To get a Bindables DP at runtime, I used to get it like this :

DependencyPropertyDescriptor dependencyPropertyDescriptor =
    DependencyPropertyDescriptor.FromName(
        nameof(Test),
        typeof(MainWindow),
        typeof(MainWindow));

It worked well before, but now it always return null. Maybe your code is not to blame as I can reproduce this behavior when leaving Bindables.Fody at 0.4 and updating Fody to 3.0.

Do you know why this happens?
Any other way to get a reference to the DP at runtime?

I've tried the code from a MSDN post and it results in the same behavior.

DependencyProperty dp = (DependencyProperty)typeof(MainWindow).GetField("TestProperty").GetValue(this);

Here's a sample project with Bindables.Fody 0.4 and Fody 2.0, it runs correctly, updating either Bindables or Fody will result in a custom exception being thrown.

BindablesDependencyPropertyDescriptor.zip

.NET 4.5.2 compatibility

It would be helpful if this could target .net 4.5.2. Is there any reason that the target framework can't be changed from 4.6 to 4.5.2?
The project was still able to build and pass the tests locally for me by simply changing the target framework for Bindables.csproj, but I don't know enough about weaver development to know if there are other gotchas in the pipeline.

Code generation not worked

The decompiled source code still contains the attribute [DependencyProperty] and no DependencyProperty was created automatically. I'm using the latest version without Fody and so I didn't create "FodyWeavers.xml".
I didn't see any messages while building.

What have I done wrong? Thank you very much in advance.

Screenshot from IlSpy:
grafik

I'm using:

  • Visual Studio 2019 Enterprise (x64)
  • .NET Framework 4.6.1

Explicitly inherits in code behind if XAML used

When we use XAML, we have to explicitly inherit in partial in code behind, even though it is not necessary.

If class ClassA inherits from ClassB and ClassB inherits from ClassC, then we have to explicitly provide inheritance in and of class ClassA and ClassB, just because of the generator requirement.

It would be better, don't add explicitly inherit in code behind then.

Bindables v4.0.0 reference problem .NET Core 3.0 preview

Hmm. In my case issue #11 appeared again with v4.0.0.
In v0.6.0 the project built successfully with
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
line deleted. Now line missing after package updated and cannot build project again.
VS2019/.NET Core 3.0 preview.
Why Bindables package has no dependency on Fody? Is it okay?
UPD:
Please, add .NET Core support.
#11 behaviour was the same both in .NET Framework 4.7.1 and in .NET Core 3.0 - Bindables worked with the line deleted.

Support for `CoerceValueCallback` in Source Generator

The Fody variant of this package is marked as deprecated on NuGet, but it seems like the Source Generator version can not yet replace all usage scenarios, as there is currently no support for CoerceValueCallback/OnCoerceValue.

Would be great if the new package had feature parity, or an alternative/workaround was acknowledged in the README.

Bindables reference problem .NET Framework 4.7.1

Issue appeared after Bindables updated to 0.6.0 and some other packages updated.
Each time after .NET Framework 4.7.1 WPF class library project closed and than opened VS as well as Resharper cannot resolve Bindables reference.
After uninstall and then install Bindables, Resharper build successfully resolve reference and can build the project, VS build still cannot resolve reference and build the project.

Error: Out of date version of Mono.Cecil.dll

Hello,
When installing this extension....I get the error below when rebuilding project. Is there any way to fix it? I tried current and prior versions, but the error pops up every time. Thanks.

Fody: The weaver assembly 'Bindables.Fody, Version=0.3.1.0, Culture=neutral, PublicKeyToken=null' references an out of date version of Mono.Cecil.dll (cecilReference.Version). At least version 0.10 is expected. The weaver needs to add a NuGet reference to FodyCecil version 2.0.

Error when trying to run tests dependant on libs using Bindables

I have a .NET Core 3.1 WPF app, which is using Bindables.
When I'm trying to run tests using 'dotnet test' on a test project, which have a reference to the main project. I get the following error:

Could not find file '%User_Folder%.nuget\packages\bindables.fody\6.0.0\Bindables.Fody.dll'

There is a file in netclassicweaver subfolder, but when I copy it to the required destination, I get the following error:

MSBUILD : error : Fody: An unhandled exception occurred: [%MyProject.cshtml_Path%]
MSBUILD : error : Exception: [%MyProject.cshtml_Path%]
MSBUILD : error : Failed to execute weaver C:\Users\maxim.nuget\packages\bindables.fody\6.0.0\build..\Bindables.Fody.dll [%MyProject.cshtml_Path%]
MSBUILD : error : Type: [%MyProject.cshtml_Path%]
MSBUILD : error : System.Exception [%MyProject.cshtml_Path%]
MSBUILD : error : StackTrace: [%MyProject.cshtml_Path%]
MSBUILD : error : at InnerWeaver.ExecuteWeavers() in C:\Myprojects\fody\FodyIsolated\InnerWeaver.cs:line 210 [%MyProject.cshtml_Path%]
MSBUILD : error : at InnerWeaver.Execute() in C:\Myprojects\fody\FodyIsolated\InnerWeaver.cs:line 111 [%MyProject.cshtml_Path%]
MSBUILD : error : Source: [%MyProject.cshtml_Path%]
MSBUILD : error : FodyIsolated [%MyProject.cshtml_Path%]
MSBUILD : error : TargetSite: [%MyProject.cshtml_Path%]
MSBUILD : error : Void ExecuteWeavers() [%MyProject.cshtml_Path%]
MSBUILD : error : Could not load type 'System.Windows.DependencyPropertyKey' from assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. [%MyProject.cshtml_Path%]
MSBUILD : error : Type: [%MyProject.cshtml_Path%]
MSBUILD : error : System.TypeLoadException [%MyProject.cshtml_Path%]
MSBUILD : error : StackTrace: [%MyProject.cshtml_Path%]
MSBUILD : error : at Bindables.Fody.DependencyPropertyWeaver..ctor(ModuleDefinition moduleDefinition) [%MyProject.cshtml_Path%]
MSBUILD : error : at Bindables.Fody.ModuleWeaver.Execute() [%MyProject.cshtml_Path%]
MSBUILD : error : at InnerWeaver.ExecuteWeavers() in C:\Myprojects\fody\FodyIsolated\InnerWeaver.cs:line 198 [%MyProject.cshtml_Path%]
MSBUILD : error : Source: [%MyProject.cshtml_Path%]
MSBUILD : error : Bindables.Fody [%MyProject.cshtml_Path%]
MSBUILD : error : TargetSite: [%MyProject.cshtml_Path%]
MSBUILD : error : Void .ctor(Mono.Cecil.ModuleDefinition) [%MyProject.cshtml_Path%]
MSBUILD : error : [%MyProject.cshtml_Path%]

CodeAnalysis DLLs part of output

Using this package causes Microsoft.CodeAnalysis.CSharp.Workspaces to be a transitive runtime dependency, dumping multiple large (several MB) DLLs into the output directory.

It feels like this should not be necessary.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.