Giter Club home page Giter Club logo

wpf's Introduction

Windows Presentation Foundation (WPF)

.NET Foundation Build Status MIT License

Windows Presentation Foundation (WPF) is a UI framework for building Windows desktop applications.

WPF supports a broad set of application development features, including an application model, resources, controls, graphics, layout, data binding and documents. WPF uses the Extensible Application Markup Language (XAML) to provide a declarative model for application programming.

WPF's rendering is vector-based, which enables applications to look great on high DPI monitors, as they can be infinitely scaled. WPF also includes a flexible hosting model, which makes it straightforward to host a video in a button, for example.

Visual Studio's designer, as well as Visual Studio Blend, make it easy to build WPF applications, with drag-and-drop and/or direct editing of XAML markup.

As of .NET 6.0, WPF supports ARM64.

See the WPF Roadmap to learn about project priorities, status and ship dates.

WinForms is another UI framework for building Windows desktop applications that is supported on .NET (7.0.x/6.0.x). WPF and WinForms applications only run on Windows. They are part of the Microsoft.NET.Sdk.WindowsDesktop SDK. You are recommended to use the most recent version of Visual Studio to develop WPF and WinForms applications for .NET.

To build the WPF repo and contribute features and fixes for .NET 8.0, Visual Studio 2022 Preview is required.

Getting started

Status

  • We are currently developing WPF for .NET 8.

See the WPF roadmap to learn about the schedule for specific WPF components.

Test published at separate repo Tests and have limited coverage at this time. We will add more tests, however, it will be a progressive process.

The Visual Studio WPF designer is now available as part of Visual Studio 2019.

How to Engage, Contribute and Provide Feedback

Some of the best ways to contribute are to try things out, file bugs, join in design conversations, and fix issues.

.NET Framework issues

Issues with .NET Framework, including WPF, should be filed on VS developer community, or Product Support. They should not be filed on this repo.

Relationship to .NET Framework

This code base is a fork of the WPF code in the .NET Framework. .NET Core 3.0 was released with a goal of WPF having parity with the .NET Framework version. Over time, the two implementations may diverge.

The Update on .NET Core 3.0 and .NET Framework 4.8 provides a good description of the forward-looking differences between .NET Core and .NET Framework.

This update states how going forward .NET Core is the future of .NET. and .NET Framework 4.8 will be the last major version of .NET Framework.

Code of Conduct

This project uses the .NET Foundation Code of Conduct to define expected conduct in our community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at [email protected].

Reporting security issues and security bugs

Security issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) [email protected]. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the MSRC PGP key, can be found in the Security TechCenter.

Also see info about related Microsoft .NET Core and ASP.NET Core Bug Bounty Program.

License

.NET Core (including the WPF repo) is licensed under the MIT license.

.NET Foundation

.NET Core WPF is a .NET Foundation project.

See the .NET home repo to find other .NET-related projects.

wpf's People

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  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  avatar  avatar

Watchers

 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  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  avatar  avatar

wpf's Issues

Document Microsoft Patent grants/licensing/etc...

Motivation
The MIT license grants a license for the source w.r.t. copyright, but not any patents that Microsoft may have that cover the software. Even using this software for its intended purpose, i.e. writing Windows apps, potentially exposes users to patent infringement liability.

Suggestion
It would be nice to have some documentation from Microsoft that includes:

  • What Microsoft-owned patents might cover functionality in WPF.
  • Which of those patents already have public grants/licenses such as OIN, and under what terms.
  • Instructions for licensing said patents, if not covered by an existing grant.

Markup compiled XAML 2009

XAML 2009 has been out for a few years now, and includes some features that would be quite nice to use with WPF in markup compiled XAML. What currently blocks XAML 2009 support? Where could community contributions help to move it forward?

Allow registering xmlns prefixes using the `using:[namespace]` syntax

It would be great if we could extend the syntax for registering xmlns prefixes to adopt the pattern used by UWP ( documented here ), and achieve a little more consistency between the two XAML Flavors.

Currently we have two options:

  1. Use the namespace and assembly name with the following syntax:
<MyObject xmlns="clr-namespace:MyClassNamespace;assembly=MyAssemblyName" />
  1. The second option is to register a prefix in the assembly itself using the xmlnsprefix attribute:
[assembly: XmlnsPrefix("http://schemas.dotMorten.com/2018", "custom")]
[assembly: XmlnsDefinition("http://schemas.dotMorten.com/2018", "MyClassNamespace")]
<MyObject xmlns="http://schemas.dotMorten.com/2018" />

The first one is rather verbose and tied to a single specific assembly, and the second one has to be done at the assembly level, which isn't possible if you don't own the assembly. Secondly it's yet-another-difference from UWP XAML, which could easily be remedied with the following syntax:

<MyObject xmlns="using:MyClassNamespace" />

I made a tiny prototype in System.Xaml to accomplish this. While it's far from the most efficient way, it proves that it can be done in WPF, by adding the following to XamlSchemeContext.cs in the GetXamlNamespace method:

            if (xmlns.StartsWith("using:"))
            {
                var ns = xmlns.Substring(6);
                foreach(var a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    if (a.ExportedTypes.Where(t => t.GetTypeInfo().Namespace == ns).Any())
                    {
                        if(xamlNamespace == null)
                            xamlNamespace = new XamlNamespace(this);
                        xamlNamespace.AddAssemblyNamespacePair(new AssemblyNamespacePair(a, ns));
                        continue;
                    }
                }
                if (xamlNamespace != null)
                    return xamlNamespace;
            }

(also I got a branch with this change here)
There's obviously a performance issue with this approach, as it requires iterating all loaded assemblies each time the namespace declaration is encountered, but considering assemblies getting loaded and unloaded is already being tracked, I think it should be possible to piggy-back on that and maintain a cache of namespaces in each assembly.

Screenshot from this implementation in use:
image

I'd be happy to volunteer for this work, but would appreciate a few tips wrt ensuring performance and caching of the lookups.

#60

Publish System.Xaml as a separate nuget package.

There is a lot of code in production that uses System.Xaml separetely from WPF on server-side for purposes that aren't related to UI in any way, shape or form.
It's worth as a separate package and will be useful right now even without .NET Core 3.0 and working WPF.
I believe it could be shipped for netstandard2.0 to make it useful in .NET Standard libraries.

Use nameof(SRID.PropertyName) syntax instead of depending on GenerateResxSource.GenerateResourcesCodeAsConstants

The codebase currently uses SRID.PropertyName syntax pervasively. This is supplied by an Arcade build task GenerateResxSource to which I have added an additional support for this particular case via GenerateResourcesCodeAsConstants.

There are ~7k instances across the codebase, and ~1k instances of these are likely coming from generated code. Once we have all the code generators ported over to .NET Core, we need to clean up everything and switch them over to use nameof(SRID.PropertyName) syntax.

Improved INotifyCollectionChanged Handling

This is a carry over from .NET Framework.

If INotifyCollectionChanged.CollectionChanged -> NotifyCollectionChangedEventArgs.NewItems has more than one item, most WPF controls will throw an exception.

The main reason for this original design is that ObservableCollection doesn't have an AddRange method and the controls assum that nothing else will support INotifyCollectionChanged.

Bring win2d to WPF

Win2D is an easy-to-use Windows Runtime API for immediate mode 2D graphics rendering with GPU acceleration.

Can we bring win2d to WPF?

PresentationTraceSources.TraceLevel not found

  • .NET Core Version: 3.0 Preview1
  • Windows version: 10, 1803
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: No (well not on 4.5 for sure)

Problem description:
attempting to use PresentationTraceSources.TraceLevel causes failure to compile with the error:
error MC3045: Unknown property 'PresentationTraceSources.TraceLevel' for type 'System.Windows.Data.Binding' encountered while parsing a Markup Extension.

Works fine in WPF on the .net framework.

Expected behavior:
Should compile and run and trace bindings

Minimal repro:
<TextBox Grid.Row="0" Text="{Binding PresentationTraceSources.TraceLevel=High}" Grid.Column="1"/>

Stefan

Make Setter.Value the ContentProperty for Setter

Currently, when you want to set the value of a setter to a complex object (e.g. control template), you have to specify the <Setter.Value> element:

<Style TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                ...
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

But this element brings no value at all, it just adds noise. Making Value the ContentProperty for Setter would make the code a bit less verbose:

<Style TargetType="Button">
    <Setter Property="Template">
        <ControlTemplate TargetType="Button">
            ...
        </ControlTemplate>
    </Setter>
</Style>

(note: I tried to make this change, but I can't find the Setter class anywhere in the repo... nor can I find any of the controls. Where are they? Is there another repo?)

First-class support for custom themes

It is currently not possible to use a custom theme as a drop-in replacement for a system theme. While it is possible to style everything, it requires more cumbersome work that is easily missed.

For example:

  • Custom styles outside of the custom theme (e.g. local styles in a UserControl) always require an explicit BasedOn="{StaticResource {x:Type ...}}" or else they are based on the system theme.
  • Inheritance does not work. Normally ListView without a GridView uses the ListBox style, but providing a custom one is not enough, it has to be explicitly set on the ListView.
  • Providing a style for ContextMenu does not style the built-in one of textboxes or scrollbars. A prominent example where this can be seen is Visual Studio:
    wpf1

My high-quality Aero themes for WPF use reflection and method hooking to solve these problems (But that's just a brittle hack. In fact, it breaks on .NET Core because tiered compilation makes hooking more difficult.). It does so by replacing System.Windows.SystemResources.FindDictionaryResource, normally responsible for locating the theme resource assembly and style for a given type or resource key, with one that can load custom resource dictionaries.

So my wish would be for adoption of a public API to set policies for resource loading, at least for PresentationFramework.dll.

_IsShipping should always be false

only a transport (nuget) package is produced from this build. it prevents publishing of symbols and the nuget package will automatically say it's nonshipping

DragLeave handlers can modify AllowedEffects of following DragEnter handlers

  • .NET Core Version: 3.0.100-preview-009812
  • Windows version: 1809
  • Does the bug reproduce also in WPF for .NET Framework 4.8? Yes

Project maintainers will consider changes that improve the product or fix known bugs (please file issues to make bugs "known").

Re-reporting a bug I previously reported against Desktop Framework WPF which was decided not to get fixed because "it isn't broken enough to require a fix". My opinion differs so I'll try again to get this fixed.

Problem description:
DragLeave handlers can modify the AllowedEffects of the following DragEnter handler by modifying their DragEventArgs.Effects property. Can happen accidently when pushing all the different drag events through a common handler. The problem is transient (fixes itself on the next mouse move because the DragLeave handler won't be called again) but causes cursor flickering due to the incorrect AllowedEffects in DragEnter. If the DragLeave handler is in a 3rd party control you can't easily fix the cursor flickering.

Root cause is that effects are passed by-ref (input is AllowedEffects, output is Effects) to two drag handlers in succession in DragDrop.cs, OleDragOver implementation at line 1024 and line 1033.

The simplest fix would be to store the original effect variable before calling the DragLeave handler and restore it before calling the DragEnter handler.

Actual behavior:
AllowedEffects in DragEnter handler are wrong if the DragLeave handler was setting DragEventArgs.Effects - in the given example this manifests itself in a flickering cursor when starting a drag from the green area and moving the cursor between red and blue areas. When you have more complex behavior attached to D&D like a thumbnail following the cursor this can get even more obvious.

Expected behavior:
AllowedEffects in DragEnter handler should match those specified by the drag originator and be independent of whatever DragLeave handlers returned from their DragEventArgs.Effects

Minimal repro:

<Window x:Class="MyWPFApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Border Grid.Row="0" Grid.ColumnSpan="2"
                MouseLeftButtonDown="StartDrag"
                Background="DarkGreen">
            <TextBlock Foreground="White" Text="drag from here"
                       HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Border>
        <Border Grid.Row="1" Grid.Column="0" AllowDrop="True"
                DragEnter="CopyDragHandler"
                DragOver="CopyDragHandler"
                DragLeave="CopyDragHandler"
                Drop="CopyDragHandler"
                Background="DarkRed">
            <TextBlock Foreground="White" Text="accepts copy"
                       HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Border>
        <Border Grid.Row="1" Grid.Column="1" AllowDrop="True"
                DragEnter="LinkDragHandler"
                DragOver="LinkDragHandler"
                DragLeave="LinkDragHandler"
                Drop="LinkDragHandler"
                Background="DarkBlue">
            <TextBlock Foreground="White" Text="accepts link"
                       HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Border>
    </Grid>
</Window>
using System.Windows;
using System.Windows.Input;

namespace MyWPFApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void StartDrag(object sender, MouseButtonEventArgs e)
        {
            DragDrop.DoDragDrop((DependencyObject)sender, "data", DragDropEffects.Copy | DragDropEffects.Link);
        }

        private void CopyDragHandler(object sender, DragEventArgs e)
        {
            e.Effects = e.AllowedEffects & DragDropEffects.Copy;
        }

        private void LinkDragHandler(object sender, DragEventArgs e)
        {
            e.Effects = e.AllowedEffects & DragDropEffects.Link;
        }
    }
}

Startup cost of XamlServices parsing is 27% slower on .NETCore than on .NET Framework

  • .NET Core Version: 3.0 Preview1
  • Windows version: 1803
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: No

Problem description:
I expected/hoped that with the XmlReader hopefully being Span<T> based. the XAML parser would be faster in .NET Core than the .NET Framework equivalent. However that's not what I'm seeing with this benchmark:

    public class BenchmarkTests
    {
        static readonly string xamlString = @"<MyObject xmlns=""clr-namespace:XamlBenchmark;assembly=XamlBenchmark"" StringProperty=""Hello World"" Int32Property=""1234"" DoubleProperty=""123.4567890"" FloatProperty=""-0.9876"" />";

        [Benchmark]
        public object Test1()
        {
            object instance = System.Xaml.XamlServices.Parse(xamlString);
            return instance;
        }
    }
    public class MyObject
    {
        public string StringProperty { get; set; }
        public int Int32Property { get; set; }
        public double DoubleProperty { get; set; }
        public float FloatProperty { get; set; }
    }

Here are the results:

BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17763.1 (1809/October2018Update/Redstone5)
Intel Xeon CPU E5-1620 v3 3.50GHz, 1 CPU, 8 logical and 4 physical cores
  [Host]     : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3190.0
  Job-FQKGZY : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3190.0
  Job-YTBJBT : .NET Core 3.0.0-preview-27122-01 (CoreCLR 4.6.27121.03, CoreFX 4.7.18.57103), 64bit RyuJIT

Method Runtime Toolchain Mean Error StdDev Ratio RatioSD
Test1 Clr net472 363.3 us 7.139 us 7.639 us 1.00 0.00
Test1 Core netcoreapp3.0 461.6 us 9.078 us 8.048 us 1.27 0.03

VisualStateGroup not working

  • .NET Core Version: 3.0 Preview1 (3.0.100-preview-009812)
  • Windows version: win10 1809 17763
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: No

Problem description:
This is probably a know issue of the first preview, very excited about this thing by the way!

Running my app, I get exceptions for windows that contain a System.Windows.VisualStateGroup(only tested via xaml). See below.
I had this on three different windows and removing the VisualStateGroup fixes it. (That of course also removes the functionality)

I guess this is not yet done? Known Bug? Or something real?

Actual behavior:
System.Windows.Markup.XamlParseException: "'Set connectionId threw an exception.' Line number '11' and line position '14'."
Inner Exception:
InvalidCastException: Unable to cast object of type 'System.Windows.VisualStateGroup' to type 'System.Windows.Shapes.Ellipse'.

Expected behavior:
Should work as it does in dotnet framework.

Minimal(ish) repro:

<Grid Name="TheEllipse" MouseUp="TheEllipse_MouseUp">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup Name="MouseStates">
            <VisualState Name="MouseEnter">
                <Storyboard>
                    <ColorAnimation To="#A1A1A1" Duration="00:00:00.3" Storyboard.TargetName="BackFill" Storyboard.TargetProperty="(SolidColorBrush.Color)" />
                </Storyboard>
            </VisualState>
        </VisualStateGroup>
   </VisualStateManager.VisualStateGroups>
   <Ellipse Stroke="Black" StrokeThickness="1">
       <Ellipse.Fill>
           <SolidColorBrush x:Name="BackFill" Color="#F1F1F1" />
       </Ellipse.Fill>
   </Ellipse>
</Grid>

Allow registering xmlns prefixes for foreign assemblies

As pointed out in #45, using

[assembly: XmlnsPrefix("http://schemas.dotMorten.com/2018", "custom")]
[assembly: XmlnsDefinition("http://schemas.dotMorten.com/2018", "MyClassNamespace")]

only works for assemblies you own.

It would be nice if you could declare those attributes at application level, to provide controls of an assembly with custom namespaces, if they lack those attributes, or even override them.

While the later one isn't essential, i think the first one could be useful, if people share their controls on nuget and don't know about custom namespace prefixes.

At least i've had situations where i was annoyed with the awfully verbose prefixes others chose, or the lack of them alltogether.

Another scenario would be that you are supplied with a viewmodels assembly and are going to use those in your views. Being able to group those namespaces would be neat.

Can we build xaml to XBF in WPF?

WPF should cost too many time to parse the xaml during startup. In UWP, we can build xaml to XBF that the binary representation enables performance advantages versus loading and parsing a XAML file as text.

ObjectWriterContext.GetDestinationType may throw null reference exception

  • .NET Core Version: (e.g. 3.0 Preview1, or daily build number, use dotnet --info)
  • Windows version: Windows 10 17025
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: do not know

Problem description:

ObjectWriterContext.GetDestinationType may throw null reference exception when CurrentFrame.Previous is not ObjectWriterFrame.

Actual behavior:

The code is in wpf/src/Microsoft.DotNet.Wpf/src/System.Xaml/System/Xaml/Context/ObjectWriterContext.cs

    internal XamlType GetDestinationType()
    {
        ObjectWriterFrame frame = _stack.CurrentFrame;

        if (frame == null)
        {
            return null;
        }

        if (frame.Instance != null && frame.XamlType == null) // when true
        {
            //
            // Text/TypeConverter, we need to go up a frame
            frame = frame.Previous as ObjectWriterFrame; // when the  frame.Previous is not ObjectWriterFrame that the frame is null
        }

        // for frame is null, calling the frame.Member will break
        if (frame.Member == XamlLanguage.Initialization) 
        {
            return frame.XamlType;
        }
        return frame.Member.Type;
    }      

if (frame.Member == XamlLanguage.Initialization)

Expected behavior:

We should check the frame = frame.Previous as ObjectWriterFrame; and the frame is not null.

Minimal repro:

Allow BitmapSource to invalidate its image cache ptr

The BitmapImage is rather nice, in that it doesn’t start downloading from the provided URI until it’s being rendering, which is great for efficiency.
The problem though is that if that URI requires some sort of specialized authentication, it doesn’t work.

So naturally I set out to create a more custom BitmapSource that mimics what BitmapImage does but uses a different mechanism to download the bytes. The problem however is that it isn’t working. There’s an internal Boolean ‘_needsUpdate’ inside BitmapSource that prevents the update after the first (empty) render, and no public method to flip the switch back. You can see this behavior in reference source where _convertedDUCEPtr doesn’t get cleared out:
https://referencesource.microsoft.com/#PresentationCore/Core/CSharp/System/Windows/Media/Imaging/BitmapSource.cs,1065
https://referencesource.microsoft.com/#PresentationCore/Core/CSharp/System/Windows/Media/Imaging/BitmapSource.cs,1701

So my proposal is to add a protected void Invalidate() method to BitmapSource that does exactly that.

Here’s an example of a reproducer image source that mimics updating the source at any point (in this case manually by calling Refresh() and generating random pixels):

    public class RandomizedImageSource : BitmapSource
    {
        private Random R = new Random();

        public RandomizedImageSource(int width, int height)
        {
            PixelWidth = width;
            PixelHeight = height;
        }

        public void Refresh()
        {
            //Flip the _needsUpdate flag to true.
            //If we don't do this, the cached bitmap would be used and the image won't update
            var field = typeof(BitmapSource).GetField("_needsUpdate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            field?.SetValue(this, true);
            //Trigger a re-render by calling this which will trigger the "FireChanged" event on the freezable
            WritePostscript();
        }

        protected override Freezable CreateInstanceCore() => new RandomizedImageSource(PixelWidth, PixelHeight);        
        public override void CopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset) => R.NextBytes((byte[])pixels);
        public override bool IsDownloading => false;
        public override PixelFormat Format => PixelFormats.Bgra32;
        public override int PixelWidth { get; }
        public override int PixelHeight { get; }
        public override double DpiX => 96;
        public override double DpiY => 96;
        public override BitmapPalette Palette => null;
        public override event EventHandler<ExceptionEventArgs> DecodeFailed;
    }

Note the reflection code - It just doesn’t work without flipping that flag.

An alternative solution would be to just flip the flag in the OnChanged method which gets called when calling WritePostscript() which in turn calls the internal FireChanged method:

        protected override void OnChanged()
        {
            var field = typeof(BitmapSource).GetField("_needsUpdate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            field?.SetValue(this, true);
            base.OnChanged();
        }

The benefit of this approach would be no new API, but it could affect existing behavior, and anyone forgetting to call base.OnChanged would not get this benefit.

There’s at least a few other use-cases you could use this for, like for example auto-refreshing, placeholder image while downloading etc.

I'm up for providing the PR for this, but would appreciate some guidance which of the two proposed methods should be used (the second one doesn't require an API change, but on the other hand might be a behavior change)

build error from artifact (Duplicate attribute in AssemblyInfo.cs)

  • .NET Core Version: (e.g. 3.0 Preview1, or daily build number, use dotnet --info)
    3.0.100-preview-009750

  • Windows version: (winver)
    Version 1809 (OS Build 17763.134)

  • Does the bug reproduce also in WPF for .NET Framework 4.8?: No

Problem description:

When trying to build a basic WPF project for dotnet core 3.0 I get multiple duplicate attribute errors that appear to be from a temporary file (\obj\Debug\netcoreapp3.0\NetCoreWpf_xnekjbde_wpftmp.AssemblyInfo.cs) conflicting with the actual AssemblyInfo.cs file

To get this error, after a fresh install of Visual Studio 2019 preview 1 I tried to open and build a wpf dotnet core project modified using Brian Lagunis's instructions from his blog post here. The project is empty (was generated in Visual Studio 15.9.3)

Actual behavior:
6 duplicate attribute errors fail the build.
CS0579 Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute
CS0579 Duplicate 'System.Reflection.AssemblyConfigurationAttribute' attribute
CS0579 Duplicate 'System.Reflection.AssemblyFileVersionAttribute' attribute
CS0579 Duplicate 'System.Reflection.AssemblyProductAttribute' attribute
CS0579 Duplicate 'System.Reflection.AssemblyTitleAttribute' attribute
CS0579 Duplicate 'System.Reflection.AssemblyVersionAttribute' attribute

Expected behavior:
No duplicate attribute errors occur unless there are duplicate attributes in my project, in which case the error message should point to the human-made code where the error occurs.

Minimal repro:
https://github.com/KelsonBall/WpfDotnetCoreDuplicateAttributeError

Extensible rendering pipeline

Motivation

Current WPF implementation relies on DirectX/etc... to render vector graphics/UI. There is potentially a desire to use alternative rendering APIs (SkiaSharp, et. al.) for specific purposes, primarily integration within other environments.

Suggestion

As much as possible, refactor rendering pipeline and other platform-specifics to be extensible, allowing for custom implementations decoupled from DirectX/etc..., for example: a SkiaSharp backend instead of a DirectX one.

Potential Questions

Question: "Why not just use Xamarin.Forms? There's already a system there for custom renderers."
Answer: Xamarin.Forms implements something similar, allowing for platform specific or custom renderers for specific controls. However WPF and Xamarin.Forms have different scopes and use cases.

[Question] Relationship with AvaloniaUI

Hello guys.

It's really wonderful to see this repo and hear about porting WPF to .Net Core.

However, I've heard a lot about how WPF is closely tied to Windows and DirectX, so it seems to me to virtually impossible to just port it as it is.

OTOH we have an Avalonia project that tries to write it from scratch on .net core for last several years.

Do you guys plan to somehow interop with them? Maybe it worth taking some ideas/approaches/etc? Or you just want to port WPF as it is?

It's not a technical task, but I have a huge interest in WPF and asking this question. I'd like to hear as much information as possible.

And thank you for your job.

Make FrameworkElement.Triggers support more types of triggers

FrameworkElement.Triggers now only accepts EventTriggers type, and we have to write a Style to add other triggers to the element, as shown below:

        <Button>
            <Button.Style>
                <Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
                    <Style.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Background" Value="Gray" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>

I think we need a more simplified xaml syntax to add triggers (Trigger, DataTrigger, MultiTrigger and MultiDataTrigger), just like below:

        <Button>
            <Button.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Background" Value="Gray" />
                </Trigger>
            </Button.Triggers>
        </Button>

SVG support for Image.ImageSource

SVG is a perfect match for WPF, but there's no way to display one without either using a third party library or converting it to XAML.

Serializing ResourceDictionary throws exception

  • .NET Core Version: Microsoft.WindowsDesktop.App 3.0.0-alpha-27122-4
  • Windows version: (winver) 17763.167
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: No

Problem description:

This writes a ResourceDictionary to disk, then I load it immediately. However… this causes the following exception:

System.Windows.Markup.XamlParseException: ''Cannot set unknown member 'System.Windows.ResourceDictionary.IsReadOnly'.' Line number '2' and line position '21'.'

Below is the resource dictionary generated by the XamlWriter:

<?xml version="1.0" encoding="utf-8"?>
<ResourceDictionary IsReadOnly="False" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Color x:Key="Fluent.Ribbon.Colors.AccentColor80">#CCD24726</Color>
    <Color x:Key="Fluent.Ribbon.Brushes.AccentColorBrush60">#99D24726</Color>

    ….
</ResourceDictionary>

Actual behavior:

System.Windows.Markup.XamlParseException: ''Cannot set unknown member 'System.Windows.ResourceDictionary.IsReadOnly'.' Line number '2' and line position '21'.'

Expected behavior:

Successfully deserialized ResourceDictionary

Minimal repro:

            using (var writer = XmlWriter.Create(fileName, new XmlWriterSettings
            {
                Indent = true,
                IndentChars = "    "
            }))
            {
                XamlWriter.Save(resourceDictionary, writer);
                writer.Flush();
            }

            resourceDictionary = new ResourceDictionary
            {
                Source = new Uri(fileName, UriKind.Absolute)
            };

WPF Main thread gets a deadlock when stylus input thread is waiting for the window to close

  • .NET Core Version: 3.0 Preview1
  • Windows version: (Windows 10 all versions / 7 SP1)
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: Yes

Problem description:

We found two way that can make the main thread locked. And we can not write any code to solve it and it can only be circumvented.

The easiest way to reproduce this issue is to wait for the window in the main thread to close in the stylus input thread.

Actual behavior:

The first way

The first way is to write a custom class implementing StylusPlugIn and wait for a window to close in the OnStylusUp method.

Let's create a new empty window named FooWindow.

public class FooWindow : Window
{

}

Then we create a FooStylusPlugIn class to implement the StylusPlugIn with overriding the OnStylusUp method. We add some code to wait for the window to close by calling Invoke which will wait by pumping a new message loop.

public class FooStylusPlugIn : StylusPlugIn
{
    public FooStylusPlugIn(FooWindow fooWindow)
    {
    	FooWindow = fooWindow;
    }

    public FooWindow FooWindow { get; }

    /// <inheritdoc />
    protected override void OnStylusUp(RawStylusInput rawStylusInput)
    {
        FooWindow.Dispatcher.Invoke(() => FooWindow.Close());
        base.OnStylusUp(rawStylusInput);
    }
}

To combine both the critical codes above, we write some codes in the MainWindow. The FooWindow is instanced in the constructor and the StylusPlugIn is plugged in it. We also make a button in the XAML that can let us know whether the main thread is still running or not.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        _fooWindow = new FooWindow();
        StylusPlugIns.Add(new FooStylusPlugIn(_fooWindow));
        _fooWindow.Show();
    }

    private void Button_OnClick(object sender, RoutedEventArgs e)
    {
    }

    private FooWindow _fooWindow;
}

Run the project, touch the main window, and you'll find that the main window never responds to your interaction. Try to click the button to view the responding and you'll soon verify what I'm talking.

The reason is that the OnStylusUp in FooStylusPlugIn is running in the stylus input thread which is also running the inside loop of the ThreadProc method. It needs to go back to the outside loop to remove the PenContext when a window is closed. The stylus input thread is waiting for the main thread to close a window and the main thread is also waiting for the stylus input thread remove PenContext. Thus, the deadlock occurred.

The demo in github

The second way

If a touch happens exactly during a window closing, the main thread will enter a lock.

The difference between the first method and the second method is that the first one will lock both the main thread and the stylus input thread but the second one will only lock the main thread.

From the theory, we know that the PenContext should be removed correctly in the outside loop. But in the second way, the stylus input thread is firing the touch event exactly when we run the code to remove the PenContext in the stylus input thread. As you can see we need to run the code to remove PenContext in the outside loop but at this moment the code is firing the touch event in the second loop.

The firing of the touch event means the _pimcResetHandle is released. Although the main thread has also released the lock the code cannot run to the outside loop to remove the PenContext and the main thread can no longer wait for the moment when the PenContext removal is finished.

void ThreadProc()
{
    while (!__disposed)
    {
      	// The outside loop
    	// To remove or add the PenContext
    	// The main thread is waiting for its finishing.
    	RemovePenContext();

    	while (true)
    	{
    		// The inside loop
    		// Tt will be blocked by the PENIMC
    		if(!Penimc.UnsafeNativeMethods.GetPenEvent(/*wait the lock*/))
    		{
    			// If the `_pimcResetHandle` is released, this if branch will enter so the inside loop will end with the `break` and the code runs back to the outside loop.
    			break;
    		}

    		FireEvent(/*fire the touch events*/); // the code is running in this line
    		// and the `_pimcResetHandle` is released.
    		// the main thread release the `_pimcResetHandle` but the code can not go to RemovePenContext for it will no longer break. 
    	}
    }
}

The main thread has released the lock but the stylus input thread doesn't need to wait for the lock. The stylus input thread cannot go back to the outside loop to remove the PenContext and main thread can no longer wait for the moment when the PenContext removal is finished.

Expected behavior:

Minimal repro:

See https://github.com/dotnet-campus/wpf-issues/tree/master/MainThreadDeadlockWithStylusInputThread/MainThreadDeadlockWhenTouchThreadWaitForWindowClosed

WPF applications stop responding to touches after adding or removing tablet devices

  • .NET Core Version: 3.0 Preview1
  • Windows version: (Windows 10 all versions / 7 SP1)
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: Yes

Problem description:

Run any WPF application on a computer which is currently has a high CPU usage, if you keep plugging and unplugging a USB HID tablet device at the same time, the WPF applications will stop responding to touches and only respond to mouse.

Actual behavior:

c# - WPF applications stop responding to touches after adding or removing tablet devices - Stack Overflow

Expected behavior:

WPF works without touch lost.

Minimal repro:

  1. Run any WPF application
  2. Keep plugging and unplugging a USB HID tablet device
  3. Make a high CPU usage

Establish Design Process for WPF APIs and XAML

Establish Design Process for WPF APIs and XAML

WPF exposes a rich set of APIs and also the Xaml syntax. We need to establish an open design process, both for additions in general and to accept and shape community contributions. This is very similar to dotnet/apireviews and dotnet/csharplang. Those teams have established effective design processes that we can adopt for WPF. For APIs, we should just use the existing .NET API review process. For XAML, we'll need do something different. We need the WPF team to define these processes.

For folks filing issues that propose new API or Xaml syntax, please reference this issue as a way of upvoting its importance.

Add support for Color Emoji support

Currently when you render emojis in WPF, they are rendered black'n'white, and not rendering with the correct emoji color.
It would be good if we could update the text rasterizer renderers to render with the correct color.
There's a proof of concept implementation here: https://github.com/samhocevar/emoji.wpf, so perhaps @samhocevar would be willing to contribute? (I'm guessing this would be done on the DirectWrite level though)

Screenshot from Emoji.WPF
image

Documentation how this works from https://blogs.windows.com/buildingapps/2017/06/06/using-color-fonts-beautiful-text-icons/#Crwe2VHsjP5PgAXS.97 (thanks @mikedn):
image

Also for discussion: Should we have a IsColorFontEnabled property that turns this behavior on/off, and should it be default like in UWP (behavior change). Also only 8.1+ uses the D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT flag, so I'm assuming the behavior would always be black/white on Win7 and 8.0

Q) Transform XAML into C# API?

I know the code release is new and may not have everything yet but what API(s) would I use to transform XAML into a C# partial class for code behind as is done normally in WPF?

Attaching touch device on a non-touch machine fails to initialize PenIMC_cor3

Repro Steps:

  • Start any WPF NetCore3 application on a machine with no touch or stylus devices.
  • Notice that PenIMC_cor3.dll is not loaded (use windbg, lmsm).
  • Attach a touch or stylus device.

Notice the following errors and the fact that touch has failed to initialize.

ModLoad: 00007ffc14a70000 00007ffc14bd5000 C:\Program Files\dotnet\shared\Microsoft.Private.WPF\3.0.0-alpha-26828-2\PenIMC_cor3.dll(5278.aec): Windows Runtime Originate Error - code 40080201 (first chance)onecore\com\combase\dcomrem\marshal.cxx(1156)\combase.dll!00007FFC79AF9379: (caller: 00007FFC79AFA49C) ReturnHr(1) tid(aec) 80040155 Interface not registered Msg:[Failed to marshal with IID={BD2C38C2-E064-41D0-A999-940F526219C2}] onecore\com\combase\dcomrem\marshal.cxx(1077)\combase.dll!00007FFC79AFA4C9: (caller: 00007FFC79AFCDF9) LogHr(1) tid(aec) 80040155 Interface not registeredonecore\com\combase\dcomrem\marshal.cxx(1017)\combase.dll!00007FFC79AFD147: (caller: 00007FFC79AEC673) ReturnHr(2) tid(aec) 80040155 Interface not registered(5278.52cc): CLR exception - code e0434352 (first chance)ModLoad: 00007ffc74110000 00007ffc74119000 C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.0.0-preview1-26820-01\System.Diagnostics.StackTrace.dllModLoad: 00007ffc147d0000 00007ffc148d5000 C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.0.0-preview1-26820-01\System.Reflection.Metadata.dllModLoad: 00007ffc74100000 00007ffc74109000 C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.0.0-preview1-26820-01\System.Diagnostics.Tracing.dllModLoad: 00007ffc11130000 00007ffc113b2000 C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.0.0-preview1-26820-01\System.Collections.Immutable.dllWorkerOperationGetTabletsInfo.OnDoWork failed due to: System.InvalidCastException: Interface not registeredFailed to find proxy registration for IID: {BD2C38C2-E064-41D0-A999-940F526219C2}. at MS.Win32.Penimc.UnsafeNativeMethods.CoCreateInstance(Guid& clsid, Object punkOuter, Int32 context, Guid& iid) at MS.Win32.Penimc.UnsafeNativeMethods.CreatePimcManager() at MS.Win32.Penimc.UnsafeNativeMethods.get_PimcManager() at System.Windows.Input.PenThreadWorker.WorkerOperationGetTabletsInfo.OnDoWork()(5278.aec): Windows Runtime Originate Error - code 40080201 (first chance)onecore\com\combase\dcomrem\marshal.cxx(1156)\combase.dll!00007FFC79AF9379: (caller: 00007FFC79AFA49C) ReturnHr(3) tid(aec) 80040155 Interface not registered Msg:[Failed to marshal with IID={BD2C38C2-E064-41D0-A999-940F526219C2}] onecore\com\combase\dcomrem\marshal.cxx(1077)\combase.dll!00007FFC79AFA4C9: (caller: 00007FFC79AFCDF9) LogHr(2) tid(aec) 80040155 Interface not registeredonecore\com\combase\dcomrem\marshal.cxx(1017)\combase.dll!00007FFC79AFD147: (caller: 00007FFC79AEC673) ReturnHr(4) tid(aec) 80040155 Interface not registered(5278.52cc): CLR exception - code e0434352 (first chance)WorkerOperationGetTabletsInfo.OnDoWork failed due to: System.InvalidCastException: Interface not registeredFailed to find proxy registration for IID: {BD2C38C2-E064-41D0-A999-940F526219C2}. at MS.Win32.Penimc.UnsafeNativeMethods.CoCreateInstance(Guid& clsid, Object punkOuter, Int32 context, Guid& iid) at MS.Win32.Penimc.UnsafeNativeMethods.CreatePimcManager() at MS.Win32.Penimc.UnsafeNativeMethods.get_PimcManager() at System.Windows.Input.PenThreadWorker.WorkerOperationGetTabletsInfo.OnDoWork()

Build script fails building with Visual Studio 2019 Preview 1 because script is looking for MsBuild in the wrong place

  • .NET Core Version: (3.0 Preview1)
  • Windows version: (Windows 10 build 18290.1000)
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: No

Problem description:
When cloning and building using Visual Studio 2019 Preview 1, build.cmd fails by not looking for NuGet.exe in the correct directory for Preview.
Line 183 of eng/common/tools.ps1 has $script:buildDriver = Join-Path $vsInstallDir "MSBuild\15.0\Bin\msbuild.exe" where for Preview1 it should be $script:buildDriver = Join-Path $vsInstallDir "MSBuild\Current\Bin\msbuild.exe"
Actual behavior:
build fails with NuGet.exe not found
Expected behavior:
build succeeds and restores packages correctly.
Minimal repro:
clone and build under 2019 Preview 1.

The type 'x:Static' was not found

  • .NET Core Version: 3.0 Preview1
  • Windows version: Windows 10 64bit, 1809
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: No

This is a re-post of an issue posted in core, as its WPF related i believe it should be posted here instead dotnet/core#2113

Problem description:

.NET core preview 1 doesn't accept x:static in xaml, where x is being defined as xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Actual behavior:

XLS0414 The type 'x:Static' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

Expected behavior:

Works / no error like in framework

Minimal repro:
https://github.com/dotnet/core/files/2651359/CoreTest.zip
or:

<Window x:Class="CoreTest.MainWindow"
        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:local="clr-namespace:CoreTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button ToolTip="{x:Static properties:Resources.PlayButtonTooltip}"/>
    </Grid>
</Window>

Add RelativePanel control

I'd like to propose porting UWP's RelativePanel control to WPF. It's a great way to layout UI, while reducing the number of panels needed to create in order to perform such a layout. A panel like this could also form the basis for porting Adaptive Triggers down the line (as these two go really well hand-in-hand).

I have an implementation of it here that I'd be happy to contribute back to WPF:
https://github.com/dotMorten/UniversalWPF/tree/master/src/UniversalWPF.RelativePanel

I'm also hoping that the Windows UI Xaml project will soon share UWP's RelativePanel implementation, to ensure 100% consistency in behavior (AFAIK my implementation matches in behavior, but knowing that there are a lot of edge cases, I probably don't handle them all).

Command dotnet build for WPF app fails with 'File can not be found' error on Mac

  • .NET Core Version: SDK 3.0.100-preview-009812
  • OS version: macOS Mojave v 10.14.1
  • Does the bug reproduce also in WPF for .NET Framework 4.8?: No

Problem description: After creating WPF project by running dotnet -new wpf command, dotnet build command fails with file not found errors.

Actual behavior:
A sample error is displayed below. The file exists however it seems that path separator is not correct which may be causing this build failure e.g. for root path and App.xaml.

/usr/local/share/dotnet/sdk/3.0.100-preview-009812/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.WinFX.targets(243,9): error BG1002: File '/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFApp\App.xaml' cannot be found. [/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFApp/MyWPFApp.csproj]
/usr/local/share/dotnet/sdk/3.0.100-preview-009812/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.WinFX.targets(243,9): error BG1002: File 'MainWindow.xaml' cannot be found. [/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFApp/MyWPFApp.csproj]
/usr/local/share/dotnet/sdk/3.0.100-preview-009812/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.WinFX.targets(243,9): error BG1003: The project file contains a property value that is not valid. [/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFApp/MyWPFApp.csproj]

Build FAILED.

Expected behavior:
Expected dotnet build to succeed.

Minimal repro:

  1. On a Mac, I have installed lastest sdk from
    https://dotnet.microsoft.com/download/dotnet-core/3.0
  2. Executed dotnet -new wpf -o SampleWPFApp command
  3. Changed current folder in terminal to SampleWPFApp
  4. Executed dotnet build however it fails

Bringing WriteableBitmapEx into WPF?

Hi,

Is there interest in a PR to bring WirteableBitmapEx extensions for the WriteableBitmap into WPF? 🤔
https://github.com/teichgraf/WriteableBitmapEx

It's a long going and stable project I've created many years ago and keep on maintaining. It was all started because the built-in WriteableBitmap lacks functionality. Now with WPF being open source we could fix that and make it part of core WPF. 🤩

Ignore NU5125 in builds until SDK is updated

NuGet made a breaking change to deprecate "licenseUrl" in face of "license" this is breaking builds as the SDK contains references to this. For now, we should ignore this warning but remove the NoWarn when the SDK is updated.

Could the current WPF code (for netfx) be made available under MIT?

Currently some parts of WPF are available at referencesource.microsoft.com and others have been made available in the past through the " .NET Framework source stepping" sources - I think only the C++/CLI parts haven't been made available at all. However these are all under MS-RSL which prevents reusing parts in your own projects.

Since everything is in the process of being added here with changes for .NET Core, could we have the current code added to the https://github.com/Microsoft/referencesource repository under MIT?

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.