Code Monkey home page Code Monkey logo

wpf-samples's Introduction

WPF-Samples

This repo contains the samples that demonstrate the API usage patterns and popular features for the Windows Presentation Foundation in the .NET for Desktop. These samples were initially hosted on MSDN, and we are gradually moving all the interesting WPF samples over to GitHub. All the samples have been retargeted to .NET 8.0.

You can also find an archive of samples targeting .NET 4.7.2 in the netframework branch.

The samples in this repo are generally about illustrating specific concepts and may go against accessibility best practices. However, the team has spent some time illustrating accessibility best practices in a subset of these samples.

For additional WPF samples, see WPF Samples.

License

Unless otherwise mentioned, the samples are released under the MIT license

Help us improve our samples

Help us improve out samples by sending us a pull-request or opening a GitHub Issue

Questions: mail [email protected]

WPF development

For .NET 8 - main branch

These samples require Visual Studio 2022(v17.8) to build, test, and deploy, and also require the most recent .NET 8 SDK.

Get a free copy of Visual Studio 2022 Community Edition

.NET 8 SDK

For .NET 7

These samples require Visual Studio 2022(v17.7), Visual Studio 2022 for Mac (v17.6) to build, test, and deploy, and also require the .NET 7 SDK.

Get a free copy of Visual Studio 2022 Community Edition

.NET 7 SDK

For .NET 6

These samples require Visual Studio 2022(v17.2), Visual Studio 2022 for Mac (v17.6) to build, test, and deploy, and also require the .NET 6 SDK.

Get a free copy of Visual Studio 2022 Community Edition

.NET 6 SDK

WPF on .NET has been open-sourced, and is now available on Github

Using the samples

To use the samples with Git, clone the WPF-Samples repository with 'git clone https://github.com/microsoft/WPF-Samples'

After cloning the WPF-Samples respository, there will be two solution files in the root directory: WPF-Samples.sln and WPF-Samples.msbuild.sln

  • To build the samples, open one of the solution files in Visual Studio 2022 and build the solution.
  • Alternatively, navigate to the directory of a sample and build with 'dotnet build' or 'msbuild' specifying the target project file.
  • WPF-Samples.msbuild.sln contains projects that can be built only with msbuild or Visual Studio, and will not compile with dotnet build. These projects contain C++ code, for which there is no support in dotnet build

The easiest way to use these samples without using Git is to download the zip file containing the current version (using the link below or by clicking the "Download ZIP" button on the repo page). You can then unzip the entire archive and use the samples in Visual Studio 2022.

Download the samples ZIP

Notes:

  • Before you unzip the archive, right-click it, select Properties, and then select Unblock.
  • Most samples should work independently
  • By default, all the samples target .NET 8.0. (Installers for the .NET 8 SDK can be found at https://dotnet.microsoft.com/en-us/download)

For more info about the programming models, platforms, languages, and APIs demonstrated in these samples, please refer to the guidance available in MSDN. These samples are provided as-is in order to indicate or demonstrate the functionality of the programming models and feature APIs for WPF.

wpf-samples's People

Contributors

andrewst avatar anjali-wpf avatar arpitmathur avatar augustoproiete avatar ayushverma-ms avatar changeworld avatar davidshootsms avatar dipeshmsft avatar dotmorten avatar guimafelipe avatar harshit7962 avatar hugodahl avatar jjloveslife avatar korygill avatar mairaw avatar markdharper avatar mgbergweiler avatar miloush avatar mshwf avatar rchauhan18 avatar rladuca avatar rrelyea avatar ryalanms avatar singhashish-wpf avatar thraka avatar vartikav avatar vatsan-madhavan avatar vb2ae avatar williamantonrohm avatar yohskdista 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  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-samples's Issues

should evaluate all TODO in samples.

Samples can have them, just want to make a pass and see if any make Microsoft of the sample look incomplete or not well-written using good patterns and practices.

should evaluate all TODO in samples.

Samples can have them, just want to make a pass and see if any make Microsoft of the sample look incomplete or not well-written using good patterns and practices.

EditBox doesn't work well standalone

I propose to split up EditBox.cs into two halves, first of which works without GridView View requirement as the following. Second half would inherit the first.

Sorry, new to GitHub, not sure how this works.

using System.Windows.Controls;

using System.Windows.Input;

using System.Windows;

using System.Windows.Documents;

namespace EditBoxControlLibrary

{

public class EditBoxBase : TextBlock

{

    #region Static Constructor



    static EditBoxBase()

    {

        DefaultStyleKeyProperty.OverrideMetadata(typeof(EditBoxBase), new FrameworkPropertyMetadata(typeof(EditBoxBase)));

    }



    #endregion





    #region Public Methods





    public EditBoxBase()

    {

        this.Loaded += EditBoxBase_Loaded;



        _textBox = new TextBox();



        _textBox.KeyDown += new KeyEventHandler(OnTextBoxKeyDown);

        _textBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(OnTextBoxLostKeyboardFocus);

    }

   

    bool bLoadedFinished = false;//Not sure why EditBoxBase_Loaded fires twice ... 20190711

    private void EditBoxBase_Loaded(object sender, RoutedEventArgs e)

    {

        if (bLoadedFinished) return;

        bLoadedFinished = true;

        TextBlock textBlock = this as TextBlock;



        this.MouseEnter += EditBoxBase_MouseEnter;

        this.MouseLeave += EditBoxBase_MouseLeave;

        this.MouseUp += EditBoxBase_MouseUp;



        _adorner = new EditBoxBaseAdorner(textBlock, _textBox);

        AdornerLayer layer = AdornerLayer.GetAdornerLayer(textBlock); // fails on getting adorner if this is in constructor

        layer.Add(_adorner);

    }



    #endregion



    #region Protected Methods



    protected void EditBoxBase_MouseEnter(object sender, MouseEventArgs e)

    {

        if (!IsEditing)

        {

            _canBeEdit = true;

        }

    }



    protected void EditBoxBase_MouseLeave(object sender, MouseEventArgs e)

    {

        _isMouseWithinScope = false;

        _canBeEdit = false;

    }





    protected void EditBoxBase_MouseUp(object sender, MouseButtonEventArgs e)

    {

        if (e.ChangedButton == MouseButton.Right || e.ChangedButton == MouseButton.Middle)

            return;



        if (!IsEditing)

        {

            if (!e.Handled && (_canBeEdit || _isMouseWithinScope))

            {

                IsEditing = true;

            }

        }

    }



    #endregion



    #region Public Properties





    #region IsEditing





    public static DependencyProperty IsEditingProperty =

            DependencyProperty.Register(

                    "IsEditing",

                    typeof(bool),

                    typeof(EditBoxBase),

                    new FrameworkPropertyMetadata(false));





    public bool IsEditing

    {

        get { return (bool)GetValue(IsEditingProperty); }

        private set

        {

            SetValue(IsEditingProperty, value);

            _adorner.UpdateVisibilty(value);

       }

    }



    #endregion





    #endregion



    #region Private Methods





    private void OnTextBoxKeyDown(object sender, KeyEventArgs e)

    {

        if (IsEditing && (e.Key == Key.Enter || e.Key == Key.F2))

        {

            IsEditing = false;

            _canBeEdit = false;

        }

    }



    private void OnTextBoxLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)

    {

        IsEditing = false;

    }





    #endregion



    #region private variable



    private EditBoxAdorner _adorner;

    private FrameworkElement _textBox;

    private bool _canBeEdit = false;

    private bool _isMouseWithinScope = false;



    #endregion

}

}

Typo in DataBindingDemo causing NullReferenceException

Line 20 of MainWindow.cs should be

 _listingDataView = (CollectionViewSource) (Resources["ListingDataView"]);

Currently, the resource name is "listingDataView" which gives an error when checking "Show only bargains"

Window issue with two monitors when "show window contents while dragging" is disabled

Hello,

The recent DPI support in WPF (starting with .Net 4.6.2) is really nice. It helped us improve a lot our application.

However when moving a window from a monitor to another with a different DPI, the rendering is broken when the system advanced option show window contents while dragging is disabled. This issue can be reproduced with the PerMonitorDPI samples of this repository.

performanceoptions

Here are captures of what is happening:
100% to 150%
moving from a monitor with 100% scale to another monitor with 150% scale
150% to 100%
moving from a monitor with 150% scale to another monitor with 100% scale

Also note that this issue still happen in some cases even if the option show window contents while dragging is enabled. When using Win+Arrows keyboard shortcut to move the window to another monitor.

I tried to workaround it by forcing WPF to recalculate the layout or even with p/invoke some native Win32 API but it doesn't fix this.

MSDN examples missing

This is probably the wrong place to report this issue and I apologize in advance, but I cannot find a better place.

The problem is, all code examples for WPF for .net 4.5 in MSDN have disappeared! E.g. compare this to the previous version. Some topics are completely missing now, although they existed before.

Where do I report this?

Why are there more TriangleIndices than Postions in resource whose key is CubeSide06

the path is "Animation/AnimationExamples/App.xaml".

the code is below :
<MeshGeometry3D x:Key="CubeSide06" TriangleIndices="0,1,2 3,4,5 6,7,8 9,10,11 " Normals="-1,0,0 -1,0,0 -1,0,0 -1,0,0 -1,0,0 -1,0,0 " TextureCoordinates="1,0 1,1 0,1 0,1 0,0 1,0 " Positions="-0.5,-0.5,0.5 -0.5,-0.5,-0.5 0.5,-0.5,-0.5 0.5,-0.5,-0.5 0.5,-0.5,0.5 -0.5,-0.5,0.5" />
from my view the element count in Postions is 6 but in TriangleIndices there is 11 , isn`t it wrong?

Sometimes problem with 'orphaned' spaces

Sometimes the HtmlFromXamlConverter misses whitespace because it is not in a <Run> or similar tag. I hacked a fix by inserting the following code at line 46 of HtmlFromXamlConverter.cs:

            string regex = @"\>[ ]{1,}\<(?!\/)";
            Match m = Regex.Match(xamlString, regex);
            while (m != null && m.Success)
            {
                xamlString =
                      xamlString.Substring(0, m.Index + 1)
                    + "<Run xml:space='preserve'>" + new String(' ', m.Length - 2) + "</Run>"
                    + xamlString.Substring(m.Index + m.Length - 1, xamlString.Length - (m.Index + m.Length - 1));
                m = Regex.Match(xamlString, regex);
            }

Add Activation and Deactivation Sample

During one of the various ports and merges, the Activation and Deactivation sample in Application management did not make it over. We need to fix it.

UI xaml binding error

follow this path WPF-Samples/Data Binding/MasterDetailXml/MainWindow.xaml,
In the third tag "StackPanel", the "Label" should set its DataContext to "{Binding ElementName=divisionsListBox, Path=SelectedItem}", otherwise the label text will be set incorrectly.

Please notice that.

Suggestion to change default method behavior for .Children (and add it to all elements)

Dear Devs,
it is kind of a pain to iterate through the whole page xaml for finding certain items.
The default methods .Content and .Children differ on the tree which is annoying (for beginners).
Could you improve the default method like using default examples for VisualTreeHelper?

Further it is annoying being forced to cast the method
(having not the same container providing .Children method) for the IntelliCode support.

Using multiple or deep Pages could be written recursively or iteratively much faster when the type is fixed providing and the same method could be used.

This
https://stackoverflow.com/questions/636383/how-can-i-find-wpf-controls-by-name-or-type/1759923#1759923
and this
https://codereview.stackexchange.com/questions/44760/is-there-a-better-way-to-get-a-child
relates to that.

PerMonitorDpi scaling

The code for scaling fonts in a WinForms user control makes the overall size way bigger than the scaling factor. Enter a factor of 1.25, you might get 1.66 as the actual size.

Control.Scale sets the size of the child controls correctly, as per the scaling factor. However the fonts are still their original (small) size. Scaling the fonts doesn't give a correct overall ratio, and can mess up layout controls.

What's the correct way to get scaled fonts and controls to match the scalingFactor?

VisualsHitTesting is WinForm

The project VisualsHitTesting in folder VisualLayer is a WinForm application!

This should be replaced with a WPF application.

How to build LocBaml?

Use msbuild LocBaml.csproj yield an error The SDK 'Microsoft.NET.Sdk.WindowsDesktop' specified could not be found.
Downloading and installing .Net core 3.0 preview and manully create a global.json to specify the version solved this issue.
But then I ran into another one:

C:\Program Files\dotnet\sdk\3.0.100-preview6-012264\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(234,5): error NETSDK1004: Assets file 'C:\Use
rs\username\Downloads\LocBaml\obj\project.assets.json' not found. Run a NuGet package restore to generate this file. [C:\Users\gaojunxiao\Downloads\LocBaml\LocBaml.csproj]

Tried create a solution from existing project and then tried to run nuget restore, it says "nothing to do".
Anyone can help me out please?

HtmlFromXamlConverter.cs doesn't set units on CSS font-size attribute

For all I know setting the units on a CSS font-size attribute is mandatory. I updated line 162 to the following in order to make it specify the font-size in points:

css = "font-size:" 
    + Math.Round(double.Parse(xamlReader.Value, CultureInfo.InvariantCulture) / (96.0 / 72.0), 2)
      .ToString("0.##", CultureInfo.InvariantCulture) + "pt;";

This only works for when the FontSize in the XAML is specified in points and without units (as it's generated by XamlWriter.Save).

<LineBreak> support

I had an issue where the HtmlFromXamlConverter.cs didn't support simple line breaks, which I fixed by inserting the following at line 451:

                    case "LineBreak":
                        htmlElementName = "BR";
                        break;

Typo in Readme file

Should it be StackPanel instead of DockPanel?
Point to this sentence ->
"This sample shows how to use a DockPanel element to arrange three Button in a vertical stack."

Fix sample projects build break due to new SDK

Due to new SDK changes, when UseWpf is not set to true, Microsoft.NET.Sdk.WindowsDesktop should show a (suppressible) error. Due to this, all sample projects are currently not building.

We need to add a property <UseWPF>true</UseWPF> in all netcore.csproj files. We also need to remove some extraneous property values in our project files.

HtmlFromXamlConverter.cs crashes when there is a FontSize attribute on the FlowDocument itself and asFullDocument=false

It throws me a System.IndexOutOfRangeException at line 493.

   bij System.Xml.XmlTextWriter.WriteEndStartTag(Boolean empty)
   bij System.Xml.XmlTextWriter.AutoComplete(Token token)
   bij System.Xml.XmlTextWriter.WriteStartElement(String prefix, String localName, String ns)
   bij System.Xml.XmlWriter.WriteStartElement(String localName)
   bij MarkupConverter.HtmlFromXamlConverter.WriteElement(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) in C:\Users\Laïla\Downloads\Converting between RTF and HTML\C#\MarkupConverter\HtmlFromXamlConverter.cs:regel 530
   bij MarkupConverter.HtmlFromXamlConverter.WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) in C:\Users\Laïla\Downloads\Converting between RTF and HTML\C#\MarkupConverter\HtmlFromXamlConverter.cs:regel 379
   bij MarkupConverter.HtmlFromXamlConverter.WriteFlowDocument(XmlTextReader xamlReader, XmlTextWriter htmlWriter, Boolean asFullDocument) in C:\Users\Laïla\Downloads\Converting between RTF and HTML\C#\MarkupConverter\HtmlFromXamlConverter.cs:regel 120
   bij MarkupConverter.HtmlFromXamlConverter.ConvertXamlToHtml(String xamlString, Boolean asFullDocument) in C:\Users\Laïla\Downloads\Converting between RTF and HTML\C#\MarkupConverter\HtmlFromXamlConverter.cs:regel 67
   bij FormatBarForRichTextBox.MainWindow.Button_Click_6(Object sender, RoutedEventArgs e) in C:\Users\Laïla\Downloads\FormatBarForRichTextBox\FormatBarForRichTextBox\FormatBarForRichTextBox\MainWindow.xaml.cs:regel 277

Whitespaces after opening tags ARE significant

Contrary to the original implementation of HtmlLexicalAnalyzer.cs, I believe whitespaces after opening tags ARE significant. Furthermore IE, Edge and Chrome seem to agree. I changed line 100 to:

_ignoreNextWhitespace = false; // Whitespaces after opening tags ARE significant

Missing ...\HostingWpfUserControlInWf\App.config file

When I attempt to build all the projects I get the following error message:

1>D:\Dev\WPF-Samples-master\Migration and Interoperability\HostingWpfUserControlInWf\App.config : error MSB3249: Application Configuration file "App.config" is invalid. Could not find file 'D:\Dev\WPF-Samples-master\Migration and Interoperability\HostingWpfUserControlInWf\App.config'.

I checked the source tree and there is no App.config in the HostingWpfUserControlInWf project files.

NETCore projects should include TargetFramework property

#66 removed TargetFrameworks . Project files should keep netcoreapp3.0 in the TargetFramework property.

Having the TargetFramework property in Directory.Build.props makes the projects not valid to open without the main solution. This is a problem since the repo has 200+ projects and waiting to load/build all to see a small project is defeating the purpose of this samples

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.