From db80384cb9e9884f0745111205b343dbaf25e039 Mon Sep 17 00:00:00 2001 From: Tris Shores <86677757+v-trisshores@users.noreply.github.com> Date: Thu, 28 Oct 2021 15:46:54 -0500 Subject: [PATCH] Content update - Custom dependency properties (user story 1878471) (#1189) * Add article, code projects, toc, and redirects * Update dotnet-desktop-guide/net/wpf/properties/custom-dependency-properties.md Co-authored-by: Andy (Steve) De George <67293991+adegeo@users.noreply.github.com> * Update dotnet-desktop-guide/net/wpf/properties/custom-dependency-properties.md Co-authored-by: Andy (Steve) De George <67293991+adegeo@users.noreply.github.com> Co-authored-by: Andy (Steve) De George <67293991+adegeo@users.noreply.github.com> --- .openpublishing.redirection.json | 8 + .../custom-dependency-properties.md | 170 ++++++++++++++++++ .../csharp/App.xaml.cs | 17 ++ .../csharp/AssemblyInfo.cs | 10 ++ .../csharp/CodeSampleCsharp.csproj | 24 +++ .../csharp/MainWindow.xaml | 5 + .../csharp/MainWindow.xaml.cs | 52 ++++++ .../csharp/Properties/Resources.Designer.cs | 63 +++++++ .../csharp/Properties/Resources.resx | 120 +++++++++++++ .../csharp/app.xaml | 9 + .../vb/Application.xaml | 9 + .../vb/Application.xaml.vb | 6 + .../vb/AssemblyInfo.vb | 11 ++ .../vb/CodeSampleVb.vbproj | 22 +++ .../vb/MainWindow.xaml | 5 + .../vb/MainWindow.xaml.vb | 54 ++++++ dotnet-desktop-guide/net/wpf/toc.yml | 2 + redirects_generator/definitions.json | 5 + 18 files changed, 592 insertions(+) create mode 100644 dotnet-desktop-guide/net/wpf/properties/custom-dependency-properties.md create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/App.xaml.cs create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/AssemblyInfo.cs create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/CodeSampleCsharp.csproj create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/MainWindow.xaml create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/MainWindow.xaml.cs create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/Properties/Resources.Designer.cs create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/Properties/Resources.resx create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/app.xaml create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/Application.xaml create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/Application.xaml.vb create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/AssemblyInfo.vb create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/CodeSampleVb.vbproj create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/MainWindow.xaml create mode 100644 dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/MainWindow.xaml.vb diff --git a/.openpublishing.redirection.json b/.openpublishing.redirection.json index 0d4f202..624c7a5 100644 --- a/.openpublishing.redirection.json +++ b/.openpublishing.redirection.json @@ -520,6 +520,14 @@ { "source_path": "dotnet-desktop-guide/framework/wpf/properties/collection-type-dependency-properties.md", "redirect_url": "/dotnet/desktop/wpf/advanced/collection-type-dependency-properties?view=netframeworkdesktop-4.8" + }, + { + "source_path": "dotnet-desktop-guide/net/wpf/advanced/custom-dependency-properties.md", + "redirect_url": "/dotnet/desktop/wpf/properties/custom-dependency-properties?view=netdesktop-5.0" + }, + { + "source_path": "dotnet-desktop-guide/framework/wpf/properties/custom-dependency-properties.md", + "redirect_url": "/dotnet/desktop/wpf/advanced/custom-dependency-properties?view=netframeworkdesktop-4.8" } ] } diff --git a/dotnet-desktop-guide/net/wpf/properties/custom-dependency-properties.md b/dotnet-desktop-guide/net/wpf/properties/custom-dependency-properties.md new file mode 100644 index 0000000..9aec98d --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/custom-dependency-properties.md @@ -0,0 +1,170 @@ +--- +title: "Custom dependency properties" +description: Learn how to implement a dependency property in Windows Presentation Foundation (WPF), and how to improve its performance, usability, or versatility. +ms.date: "10/20/2021" +ms.topic: overview +dev_langs: + - "csharp" + - "vb" +helpviewer_keywords: + - "implementing [WPF], wrappers" + - "registering properties [WPF]" + - "properties [WPF], metadata" + - "metadata [WPF], for properties" + - "custom dependency properties [WPF]" + - "properties [WPF], registering" + - "wrappers [WPF], implementing" + - "dependency properties [WPF], custom" +--- + + +# Custom dependency properties (WPF .NET) + +Windows Presentation Foundation (WPF) application developers and component authors can create custom dependency properties to extend the functionality of their properties. Unlike a common language runtime (CLR) [property](/dotnet/standard/base-types/common-type-system#properties), a dependency property adds support for styling, data binding, inheritance, animations, and default values. , , and are examples of existing dependency properties in WPF classes. This article describes how to implement custom dependency properties, and presents options for improving performance, usability, and versatility. + +## Prerequisites + +The article assumes a basic knowledge of dependency properties, and that you've read [Dependency properties overview](dependency-properties-overview.md). To follow the examples in this article, it helps if you're familiar with Extensible Application Markup Language (XAML) and know how to write WPF applications. + +## Dependency property identifier + +Dependency properties are properties that are registered with the WPF property system through or calls. The `Register` method returns a instance that holds the registered name and characteristics of a dependency property. You'll assign the `DependencyProperty` instance to a static readonly field, known as a *dependency property identifier*, that by convention is named `Property`. For example, the identifier field for the property is always . + +The dependency property identifier is used as a backing field for getting or setting property values, rather than the standard pattern of backing a property with a private field. Not only does the property system uses the identifier, XAML processors may use it, and your code (and possibly external code) can access dependency properties through their identifiers. + +Dependency properties can only be applied to classes that are derived from types. Most WPF classes support dependency properties, because `DependencyObject` is close to the root of the WPF class hierarchy. For more information about dependency properties, and the terminology and conventions used to describe them, see [Dependency properties overview](dependency-properties-overview.md). + +## Dependency property wrappers + +WPF dependency properties that aren't attached properties are exposed by a CLR wrapper that implements `get` and `set` accessors. By using a property wrapper, consumers of dependency properties can get or set dependency property values, just as they would any other CLR property. The `get` and `set` accessors interact with the underlying property system through and calls, passing in the dependency property identifier as a parameter. Consumers of dependency properties typically don't call `GetValue` or `SetValue` directly, but if you're implementing a custom dependency property you'll use those methods in the wrapper. + +## When to implement a dependency property + +When you implement a property on a class that derives from , you make it a dependency property by backing your property with a identifier. Whether it's beneficial to create a dependency property depends on your scenario. Although backing your property with a private field is adequate for some scenarios, consider implementing a dependency property if you want your property to support one or more of the following WPF capabilities: + +- Properties that are settable within a style. For more information, see [Styles and templates](../controls/styles-templates-overview.md). + +- Properties that support data binding. For more information about data binding dependency properties, see [Bind the properties of two controls](/dotnet/desktop/wpf/data/how-to-bind-the-properties-of-two-controls?view=netframeworkdesktop-4.8&preserve-view=true). + +- Properties that are settable through dynamic resource references. For more information, see [XAML resources](/dotnet/desktop-wpf/fundamentals/xaml-resources-define). + +- Properties that automatically inherit their value from a parent element in the element tree. For this, you'll need to register using , even if you also create a property wrapper for CLR access. For more information, see [Property value inheritance](/dotnet/desktop/wpf/advanced/property-value-inheritance?view=netframeworkdesktop-4.8&preserve-view=true). + +- Properties that are animatable. For more information, see [Animation overview](/dotnet/desktop/wpf/graphics-multimedia/animation-overview?view=netframeworkdesktop-4.8&preserve-view=true). + +- Notification by the WPF property system when a property value changes. Changes might be due to actions by the property system, environment, user, or styles. Your property can specify a callback method in property metadata that will get invoked each time the property system determines that your property value changed. A related concept is property value coercion. For more information, see [Dependency property callbacks and validation](/dotnet/desktop/wpf/advanced/dependency-property-callbacks-and-validation?view=netframeworkdesktop-4.8&preserve-view=true). + +- Access to dependency property metadata, which is read by WPF processes. For example, you can use property metadata to: + + - Specify whether a changed dependency property value should make the layout system recompose visuals for an element. + + - Set the default value of a dependency property, by overriding metadata on derived classes. + +- Visual Studio WPF designer support, such as editing the properties of a custom control in the **Properties** window. For more information, see [Control authoring overview](/dotnet/desktop/wpf/controls/control-authoring-overview?view=netframeworkdesktop-4.8&preserve-view=true). + +For some scenarios, overriding the metadata of an existing dependency property is a better option than implementing a new dependency property. Whether a metadata override is practical depends on your scenario, and how closely that scenario resembles the implementation of existing WPF dependency properties and classes. For more information about overriding metadata on existing dependency properties, see [Dependency property metadata](/dotnet/desktop/wpf/advanced/dependency-property-metadata?view=netframeworkdesktop-4.8&preserve-view=true). + +## Checklist for creating a dependency property + +Follow these steps to create a dependency property. Some of the steps can be combined and implemented in a single line of code. + +1. (Optional) Create dependency property metadata. + +1. Register the dependency property with the property system, specifying a property name, an owner type, the property value type, and optionally, property metadata. + +1. Define a identifier as a `public static readonly` field on the owner type. The identifier field name is the property name with the suffix `Property` appended. + +1. Define a CLR wrapper property with the same name as the dependency property name. In the CLR wrapper, implement `get` and `set` accessors that connect with the dependency property that backs the wrapper. + +### Registering the property + +In order for your property to be a dependency property, you must register it with the property system. To register your property, call the method from inside the body of your class, but outside of any member definitions. The `Register` method returns a unique dependency property identifier that you'll use when calling the property system API. The reason that the `Register` call is made outside of member definitions is because you assign the return value to a `public static readonly` field of type . This field, which you'll create in your class, is the identifier for your dependency property. In the following example, the first argument of `Register` names the dependency property `AquariumGraphic`. + +:::code language="csharp" source="./snippets/custom-dependency-properties/csharp/MainWindow.xaml.cs" id="RegisterDependencyProperty"::: +:::code language="vb" source="./snippets/custom-dependency-properties/vb/MainWindow.xaml.vb" id="RegisterDependencyProperty"::: + +> [!NOTE] +> Defining the dependency property in the class body is the typical implementation, but it's also possible to define a dependency property in the class static constructor. This approach might make sense if you need more than one line of code to initialize the dependency property. + +### Dependency property naming + +The established naming convention for dependency properties is mandatory for normal behavior of the property system. The name of the identifier field that you create must be the registered name of the property with the suffix `Property`. + +A dependency property name must be unique within the registering class. Dependency properties that are inherited through a base type have already been registered, and cannot be registered by a derived type. However, you can use a dependency property that was registered by a different type, even a type your class doesn't inherit from, by adding your class as an owner of the dependency property. For more information on adding a class as owner, see [Dependency property metadata](/dotnet/desktop/wpf/advanced/dependency-property-metadata?view=netframeworkdesktop-4.8&preserve-view=true#adding-a-class-as-an-owner-of-an-existing-dependency-property). + +### Implementing a property wrapper + +By convention, the name of the wrapper property must be the same as the first parameter of the call, which is the dependency property name. Your wrapper implementation will call in the `get` accessor, and in the `set` accessor (for read-write properties). The following example shows a wrapper—following the registration call and identifier field declaration. All public dependency properties on WPF classes use a similar wrapper model. + +:::code language="csharp" source="./snippets/custom-dependency-properties/csharp/MainWindow.xaml.cs" id="RegisterDependencyPropertyWithWrapper"::: +:::code language="vb" source="./snippets/custom-dependency-properties/vb/MainWindow.xaml.vb" id="RegisterDependencyPropertyWithWrapper"::: + +Except in rare cases, your wrapper implementation should only contain and code. For the reasons behind this, see [Implications for custom dependency properties](/dotnet/desktop/wpf/advanced/xaml-loading-and-dependency-properties?view=netframeworkdesktop-4.8&preserve-view=true#implications-for-custom-dependency-properties). + +If your property doesn't follow established naming conventions, you might run into these issues: + +- Some aspects of styles and templates won't work. + +- Most tools and designers rely on the naming conventions to properly serialize XAML and provide designer environment assistance at a per-property level. + +- The current implementation of the WPF XAML loader bypasses the wrappers entirely, and relies on the naming convention to process attribute values. For more information, see [XAML loading and dependency properties](/dotnet/desktop/wpf/advanced/xaml-loading-and-dependency-properties?view=netframeworkdesktop-4.8&preserve-view=true). + +### Dependency property metadata + +When you register a dependency property, the property system creates a metadata object to store property characteristics. Overloads of the method let you specify property metadata during registration, for example . A common use of property metadata is to apply a custom default value for new instances that use a dependency property. If you don't provide property metadata, the property system will assign default values to many of the dependency property characteristics. + +If you're creating a dependency property on a class derived from , you can use the more specialized metadata class rather than its base class . Several constructor signatures let you specify different combinations of metadata characteristics. If you just want to specify a default value, then use and pass the default value to the `Object` parameter. Ensure that the value type matches the `propertyType` specified in the `Register` call. + +Some overloads let you specify [metadata option flags]() for your property. The property system converts these flags into discrete properties and the flag values are used by WPF processes, such as the layout engine. + +#### Setting metadata flags + +Consider the following when setting metadata flags: + +- If your property value (or changes to it) affects how the layout system renders a UI element, then set one or more of the following flags: + + - , which indicates that a change in property value requires a change in UI rendering, specifically the space occupied by an object within its parent. For example, set this metadata flag for a `Width` property. + + - , which indicates that a change in property value requires a change in UI rendering, specifically the position of an object within its parent. Typically, the object doesn't also change size. For example, set this metadata flag for an `Alignment` property. + + - , which indicates that a change has occurred that doesn't affect layout and measure, but still requires another render. For example, set this flag for a `Background` property, or any other property that affects the color of an element. + + You can use also these flags as inputs to your override implementations of the property system (or layout) callbacks. For example, you might use an callback to call when a property of the instance reports a value change and has set in metadata. + +- Some properties affect the rendering characteristics of their parent element in other ways. For example, changes to the property can change the overall rendering of a flow document. Use or to signal parent actions in your own properties. + +- By default, dependency properties support data binding. However, you can use to disable data binding when there's no realistic scenario for it, or where data binding performance is problematic, such as on large objects. + +- Although the default data binding [mode]() for dependency properties is , you can change the binding mode of a specific binding to . For more information, see [Binding direction](/dotnet/desktop/wpf/data/binding-declarations-overview#binding-direction). As a dependency property author, you can even choose to make two-way binding the default mode. An example of an existing dependency property that uses two-way data binding is , which has a state that's based on other properties and method calls. The scenario for `IsSubmenuOpen` is that its setting logic, and the compositing of , interact with the default theme style. is another WPF dependency property that uses two-way binding by default. + +- You can enable property inheritance for your dependency property by setting the flag. Property inheritance is useful for scenarios in which parent and child elements have a property in common and it makes sense for the child element to inherit the parent value for the common property. An example of an inheritable property is , which supports binding operations that use the [master-detail scenario](/dotnet/desktop/wpf/data/how-to-use-the-master-detail-pattern-with-hierarchical-data?view=netframeworkdesktop-4.8&preserve-view=true) for data presentation. Property value inheritance lets you specify a data context at the page or application root, which saves having to specify it for child element bindings. Although an inherited property value overrides the default value, property values can be set locally on any child element. Use property value inheritance sparingly because it has a performance cost. For more information, see [Property value inheritance](/dotnet/desktop/wpf/advanced/property-value-inheritance?view=netframeworkdesktop-4.8&preserve-view=true). + +- Set the flag to indicate that your dependency property should be detected or used by navigation journaling services. For example, the property sets the `Journal` flag to recommend that applications keep a journaling history of items selected. + +## Read-only dependency properties + +You can define a dependency property that's read-only. A typical scenario is a dependency property that stores internal state. For example, is read-only because its state should only be determined by mouse input. For more information, see [Read-only dependency properties](/dotnet/desktop/wpf/advanced/read-only-dependency-properties?view=netframeworkdesktop-4.8&preserve-view=true). + +## Collection-type dependency properties + +Collection-type dependency properties have extra implementation issues to consider, such as setting a default value for reference types and data binding support for collection elements. For more information, see [Collection-type dependency properties](/dotnet/desktop/wpf/advanced/collection-type-dependency-properties?view=netframeworkdesktop-4.8&preserve-view=true). + +## Dependency property security + +Typically, you'll declare dependency properties as public properties, and identifier fields as `public static readonly` fields. If you specify a more restrictive access level, such as `protected`, a dependency property can still be accessed through its identifier in combination with property system APIs. Even a protected identifier field is potentially accessible through WPF metadata reporting or value determination APIs, like . For more information, see [Dependency property security](/dotnet/desktop/wpf/advanced/dependency-property-security?view=netframeworkdesktop-4.8&preserve-view=true). + +For read-only dependency properties, the value returned from is , and typically you won't make `DependencyPropertyKey` a `public` member of your class. Because the WPF property system doesn't propagate the `DependencyPropertyKey` outside of your code, a read-only dependency property has better `set` security than a read-write dependency property. + +## Dependency properties and class constructors + +There's a general principle in managed code programming, often enforced by code analysis tools, that class constructors shouldn't call virtual methods. This is because base constructors can be called during initialization of a derived class constructor, and a virtual method called by a base constructor might run before complete initialization of the derived class. When you derive from a class that already derives from , the property system itself calls and exposes virtual methods internally. These virtual methods are part of the WPF property system services. Overriding the methods enables derived classes to participate in value determination. To avoid potential issues with runtime initialization, you shouldn't set dependency property values within constructors of classes, unless you follow a specific constructor pattern. For more information, see [Safe constructor patterns for DependencyObjects](/dotnet/desktop/wpf/advanced/safe-constructor-patterns-for-dependencyobjects?view=netframeworkdesktop-4.8&preserve-view=true). + +## See also + +- [Dependency properties overview](dependency-properties-overview.md) +- [Dependency property metadata](/dotnet/desktop/wpf/advanced/dependency-property-metadata?view=netframeworkdesktop-4.8&preserve-view=true) +- [Control authoring overview](/dotnet/desktop/wpf/controls/control-authoring-overview?view=netframeworkdesktop-4.8&preserve-view=true) +- [Collection-type dependency properties](collection-type-dependency-properties.md) +- [Dependency property security](/dotnet/desktop/wpf/advanced/dependency-property-security?view=netframeworkdesktop-4.8&preserve-view=true) +- [XAML loading and dependency properties](/dotnet/desktop/wpf/advanced/xaml-loading-and-dependency-properties?view=netframeworkdesktop-4.8&preserve-view=true) +- [Safe constructor patterns for DependencyObjects](/dotnet/desktop/wpf/advanced/safe-constructor-patterns-for-dependencyobjects?view=netframeworkdesktop-4.8&preserve-view=true) diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/App.xaml.cs b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/App.xaml.cs new file mode 100644 index 0000000..3128552 --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace CodeSampleCsharp +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } +} diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/AssemblyInfo.cs b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/AssemblyInfo.cs new file mode 100644 index 0000000..8b5504e --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Windows; + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/CodeSampleCsharp.csproj b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/CodeSampleCsharp.csproj new file mode 100644 index 0000000..8824b2f --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/CodeSampleCsharp.csproj @@ -0,0 +1,24 @@ + + + + WinExe + net5.0-windows + true + + + + + True + True + Resources.resx + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/MainWindow.xaml b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/MainWindow.xaml new file mode 100644 index 0000000..f0f24b6 --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/MainWindow.xaml @@ -0,0 +1,5 @@ + + diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/MainWindow.xaml.cs b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/MainWindow.xaml.cs new file mode 100644 index 0000000..524dc50 --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/MainWindow.xaml.cs @@ -0,0 +1,52 @@ +using System; +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; + +namespace CodeSampleCsharp +{ + /// + /// Interaction logic for MainWindow.xaml. + /// + public partial class MainWindow : Window + { + } + + public class Aquarium : DependencyObject + { + // + // + // Register a dependency property with the specified property name, + // property type, owner type, and property metadata. + private static readonly DependencyProperty s_aquariumGraphicProperty = + DependencyProperty.Register( + name: "AquariumGraphic", + propertyType: typeof(Uri), + ownerType: typeof(Aquarium), + typeMetadata: new FrameworkPropertyMetadata( + defaultValue: new Uri("http://www.contoso.com/aquarium-graphic.jpg"), + flags: FrameworkPropertyMetadataOptions.AffectsRender, + propertyChangedCallback: new PropertyChangedCallback(OnUriChanged)) + ); + + // Store the dependency property identifier as a static member of the class. + public static readonly DependencyProperty AquariumGraphicProperty = + s_aquariumGraphicProperty; + // + + // Declare a read-write property. + public Uri AquariumContents + { + get => (Uri)GetValue(AquariumGraphicProperty); + set => SetValue(AquariumGraphicProperty, value); + } + // + + private static void OnUriChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) + { + Shape shape = (Shape)dependencyObject; + shape.Fill = new ImageBrush(new BitmapImage((Uri)e.NewValue)); + } + } +} diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/Properties/Resources.Designer.cs b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/Properties/Resources.Designer.cs new file mode 100644 index 0000000..64552f9 --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace CodeSampleCsharp.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CodeSampleCsharp.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/Properties/Resources.resx b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/Properties/Resources.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/Properties/Resources.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/app.xaml b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/app.xaml new file mode 100644 index 0000000..867d2f0 --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/csharp/app.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/Application.xaml b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/Application.xaml new file mode 100644 index 0000000..f225972 --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/Application.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/Application.xaml.vb b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/Application.xaml.vb new file mode 100644 index 0000000..084cbe9 --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/Application.xaml.vb @@ -0,0 +1,6 @@ +Class Application + + ' Application-level events, such as Startup, Exit, and DispatcherUnhandledException + ' can be handled in this file. + +End Class diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/AssemblyInfo.vb b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/AssemblyInfo.vb new file mode 100644 index 0000000..025ee72 --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/AssemblyInfo.vb @@ -0,0 +1,11 @@ +Imports System.Windows + +'The ThemeInfo attribute describes where any theme specific and generic resource dictionaries can be found. +'1st parameter: where theme specific resource dictionaries are located +'(used if a resource is not found in the page, +' or application resource dictionaries) + +'2nd parameter: where the generic resource dictionary is located +'(used if a resource is not found in the page, +'app, and any theme specific resource dictionaries) + diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/CodeSampleVb.vbproj b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/CodeSampleVb.vbproj new file mode 100644 index 0000000..c7ae1cc --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/CodeSampleVb.vbproj @@ -0,0 +1,22 @@ + + + + WinExe + net5.0-windows + CodeSampleVb + true + + + + + + + + + + + + + + + diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/MainWindow.xaml b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/MainWindow.xaml new file mode 100644 index 0000000..d087939 --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/MainWindow.xaml @@ -0,0 +1,5 @@ + + diff --git a/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/MainWindow.xaml.vb b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/MainWindow.xaml.vb new file mode 100644 index 0000000..261803e --- /dev/null +++ b/dotnet-desktop-guide/net/wpf/properties/snippets/custom-dependency-properties/vb/MainWindow.xaml.vb @@ -0,0 +1,54 @@ +Namespace CodeSampleVb + + ' + ' Interaction logic for MainWindow.xaml. + ' + Partial Public Class MainWindow + Inherits Window + + Public Sub New() + InitializeComponent() + End Sub + End Class + + Public Class Aquarium + Inherits DependencyObject + + ' + ' + ' Register a dependency property with the specified property name, + ' property type, owner type, and property metadata. + Private Shared ReadOnly s_aquariumGraphicProperty As DependencyProperty = + DependencyProperty.Register( + name:="AquariumGraphic", + propertyType:=GetType(Uri), + ownerType:=GetType(Aquarium), + typeMetadata:=New FrameworkPropertyMetadata( + defaultValue:=New Uri("http://www.contoso.com/aquarium-graphic.jpg"), + flags:=FrameworkPropertyMetadataOptions.AffectsRender, + propertyChangedCallback:=New PropertyChangedCallback(AddressOf OnUriChanged))) + + ' Store the dependency property identifier as a static member of the class. + Public Shared ReadOnly AquariumGraphicProperty As DependencyProperty = + s_aquariumGraphicProperty + ' + + ' Declare a read-write property. + Public Property AquariumGraphic As Uri + Get + Return CType(GetValue(AquariumGraphicProperty), Uri) + End Get + Set + SetValue(AquariumGraphicProperty, Value) + End Set + End Property + ' + + Private Shared Sub OnUriChanged(dependencyObject As DependencyObject, e As DependencyPropertyChangedEventArgs) + Dim shape As Shape = CType(dependencyObject, Shape) + shape.Fill = New ImageBrush(New BitmapImage(CType(e.NewValue, Uri))) + End Sub + + End Class + +End Namespace diff --git a/dotnet-desktop-guide/net/wpf/toc.yml b/dotnet-desktop-guide/net/wpf/toc.yml index 180eac4..9660a92 100644 --- a/dotnet-desktop-guide/net/wpf/toc.yml +++ b/dotnet-desktop-guide/net/wpf/toc.yml @@ -88,6 +88,8 @@ items: href: properties/attached-properties-overview.md - name: Collection-type dependency properties href: properties/collection-type-dependency-properties.md + - name: Custom dependency properties + href: properties/custom-dependency-properties.md - name: Common tasks items: - name: Implement a dependency property diff --git a/redirects_generator/definitions.json b/redirects_generator/definitions.json index 3dd161b..231d029 100644 --- a/redirects_generator/definitions.json +++ b/redirects_generator/definitions.json @@ -349,6 +349,11 @@ "SourceUrl": "/dotnet/desktop/wpf/advanced/how-to-implement-a-dependency-property?view=netframeworkdesktop-4.8", "TargetUrl": "/dotnet/desktop/wpf/properties/how-to-implement-a-dependency-property?view=netdesktop-5.0" }, + { + "Redirect": "TwoWay", + "SourceUrl": "/dotnet/desktop/wpf/advanced/custom-dependency-properties?view=netframeworkdesktop-4.8", + "TargetUrl": "/dotnet/desktop/wpf/properties/custom-dependency-properties?view=netdesktop-5.0" + }, // Systems - XAML {