Files
docs-desktop/dotnet-desktop-guide/net/wpf/properties/snippets/read-only-dependency-properties/csharp/MainWindow.xaml.cs
T
Tris Shores 5eff6608b9 Content update - Read-only dependency properties (user story 1878471) (#1230)
* Improve collection-type dp snippets that are readonly.

* Add article, snippets, toc, and redirects

* Minor edit

* Update target framework to .NET 6.0
2021-12-01 15:50:53 -08:00

39 lines
1.3 KiB
C#

using System.Windows;
namespace CodeSampleCsharp
{
/// <summary>
/// Interaction logic for MainWindow.xaml.
/// </summary>
public partial class MainWindow : Window
{
readonly Aquarium _aquarium = new();
private void Button_Click(object sender, RoutedEventArgs e)
{
// Test setting a value.
_aquarium.SetValue(Aquarium.FishCountPropertyKey, _aquarium.FishCount + 1);
lblFishCount.Content = $"Aquarium fish count: {_aquarium.FishCount}";
}
}
//<RegisterReadOnlyDependencyProperty>
public class Aquarium : DependencyObject
{
// Register a dependency property with the specified property name,
// property type, owner type, and property metadata.
// Assign DependencyPropertyKey to a nonpublic field.
internal static readonly DependencyPropertyKey FishCountPropertyKey =
DependencyProperty.RegisterReadOnly(
name: "FishCount",
propertyType: typeof(int),
ownerType: typeof(Aquarium),
typeMetadata: new FrameworkPropertyMetadata());
// Declare a public get accessor.
public int FishCount =>
(int)GetValue(FishCountPropertyKey.DependencyProperty);
}
//</RegisterReadOnlyDependencyProperty>
}