Giter VIP home page Giter VIP logo

Comments (4)

github-actions avatar github-actions commented on June 18, 2024

Hi I'm an AI powered bot that finds similar issues based off the issue title.

Please view the issues below to see if they solve your problem, and if the issue describes your problem please consider closing this one. Thank you!

Closed similar issues:

Note: You can give me feedback by thumbs upping or thumbs downing this comment.

from microsoft-ui-xaml.

AndrewKeepCoding avatar AndrewKeepCoding commented on June 18, 2024

This is how I'm creating the ViewModel:

public static class ViewModelCreator
{
    // Compiles at runtime and creates a ViewModel.
    // Exception thrown:
    // 'System.ArgumentNullException' in System.Private.CoreLib.dll
    public static object? CreateAtRuntime()
    {
        string viewModelCSharpCode = GetViewModelCSharpCode();
        Assembly viewModelAssemblly = CreateViewModelAssembly(viewModelCSharpCode);
        return viewModelAssemblly.CreateInstance("DynamicViewModel");
    }

    private static string GetViewModelCSharpCode()
    {
        return
            """
            public class DynamicViewModel : System.ComponentModel.INotifyPropertyChanged
            {
                private string _someText = string.Empty;

                public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged;

                public string SomeText
                {
                    get => _someText;
                    set
                    {
                        if (_someText != value)
                        {
                            _someText = value;
                            PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(nameof(SomeText)));
                        }
                    }
                }
            }
            """;
    }

    private static Assembly CreateViewModelAssembly(string viewModelCode)
    {
        CSharpCompilationOptions cSharpCompilationOptions = new(
            outputKind: OutputKind.DynamicallyLinkedLibrary,
            nullableContextOptions: NullableContextOptions.Enable);
        SyntaxTree viewModelClassSyntaxTree = CSharpSyntaxTree.ParseText(viewModelCode);

        CSharpCompilation compilation =
            CSharpCompilation.Create(
                assemblyName: "SomeAssembly",
                options: cSharpCompilationOptions,
                references: CreateReferences())
                .AddSyntaxTrees(viewModelClassSyntaxTree);

        using var stream = new MemoryStream();
        EmitResult emitResult = compilation.Emit(stream);

        if (emitResult.Success is false)
        {
            throw new Exception("Failed to compile the view model");
        }

        _ = stream.Seek(0, SeekOrigin.Begin);

        return Assembly.Load(stream.ToArray());
    }

    private static List<PortableExecutableReference> CreateReferences()
    {
        string runtimePath = RuntimeEnvironment.GetRuntimeDirectory();

        List<PortableExecutableReference> references = new()
            {
                MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(Path.Combine(runtimePath, "System.Runtime.dll")),
                MetadataReference.CreateFromFile(typeof(System.ComponentModel.INotifyPropertyChanged).GetTypeInfo().Assembly.Location),
            };

        return references;
    }
}

then in MainPage.xaml.cs:

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    // On WinUI 3, TEST 3 works BUT throws "ArgumentNullException" !
    this.DataContext = ViewModelCreator.CreateAtRuntime();
}

and in MainPage.xaml

<StackPanel>
    <TextBox Text="{Binding SomeText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
    <TextBlock Text="{Binding SomeText}" />
</StackPanel>

from microsoft-ui-xaml.

AndrewKeepCoding avatar AndrewKeepCoding commented on June 18, 2024

Background:
I'm working on an app that edits JSON files. The app has several pages that let you edit a corresponding part of the JSON. It's not just a TreeView. I need to make each page modifyable (layout, using controls, etc) without recompiling the app. That's why I'm using XamlReader and CSharpCompilation to create pages from text files at runtime.

from microsoft-ui-xaml.

AndrewKeepCoding avatar AndrewKeepCoding commented on June 18, 2024

This can also be reproduced with SetBinding:

var binding = new Binding { Path = new PropertyPath("SomeText"), Mode = BindingMode.TwoWay };
this.SomeTextBox.SetBinding(TextBox.TextProperty, binding);

and the exception is thrown here:

XamlTypeInfo.g.cs

    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.UI.Xaml.Markup.Compiler"," 3.0.0.2403")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    internal partial class XamlTypeInfoProvider
    {
        public global::Microsoft.UI.Xaml.Markup.IXamlType GetXamlTypeByType(global::System.Type type)
        {
            global::Microsoft.UI.Xaml.Markup.IXamlType xamlType;
            lock (_xamlTypeCacheByType) 
            { 
                if (_xamlTypeCacheByType.TryGetValue(type, out xamlType))
                {
                    return xamlType;
                }

from microsoft-ui-xaml.

Related Issues (20)

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.