前言
附加屬性是 WPF 中一個非常強大和獨特的概念。簡單來說,它允許一個對象為另一個在其本身類定義中未定義的屬性賦值。
1、定義附加屬性
定義一個Watermark的附加屬性,該屬性的作用是將TextBox的附加屬性改變時,TextBox的字體顏色改成灰色。
class WatermarkService{// 1. 注冊一個名為 Watermark 的附加屬性public static readonly DependencyProperty WatermarkProperty =DependencyProperty.RegisterAttached("Watermark", // 屬性名typeof(string), // 屬性類型typeof(WatermarkService), // 所有者類型new PropertyMetadata(string.Empty, OnWatermarkChanged) // 元數據,包含默認值和回調方法);// 2. 標準的 Get 訪問器public static string GetWatermark(DependencyObject obj){return (string)obj.GetValue(WatermarkProperty);}// 3. 標準的 Set 訪問器public static void SetWatermark(DependencyObject obj, string value){obj.SetValue(WatermarkProperty, value);}// 4. 屬性值改變時的回調方法private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){// 我們期望這個屬性只用在 TextBox 上if (d is TextBox textBox){string newWatermark = (string)e.NewValue;string oldWatermark = (string)e.OldValue;// 這里可以實現具體的邏輯,例如:// - 當 TextBox 文本為空時顯示水印// - 當獲得焦點時隱藏水印// 通常需要訂閱 GotFocus、LostFocus 等事件。// 這是一個簡化示例,實際實現會更復雜。if (string.IsNullOrEmpty(textBox.Text)){textBox.Text = newWatermark;textBox.Foreground = Brushes.White; // 將水印文字設置為灰色}}}}
2、xaml代碼
<Window x:Class="wpf之附加屬性.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:wpf之附加屬性"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid><StackPanel Orientation="Vertical" ><Button Height=" 100" Background="Blue" /><TextBox x:Name="tbx_test" Background="Red" local:WatermarkService.Watermark="我是附加屬性"Width="200" Height="30"/></StackPanel ></Grid>
</Window>
3、運行效果
馬工撰寫的年入30萬+C#上位機項目實戰必備教程(點擊下方鏈接即可訪問文章目錄)
1、《C#串口通信從入門到精通》
2、《C#與PLC通信從入門到精通 》
3、《C# Modbus通信從入門到精通》
4、《C#Socket通信從入門到精通 》
5、《C# MES通信從入門到精通》
6、《winform控件從入門到精通》
7、《C#操作MySql數據庫從入門到精通》