Dot-Net
如何在現有控制項上創建依賴屬性?
幾天來,我一直在閱讀 Dependency 屬性,並了解它們如何檢索值,而不是像在 CLR 屬性中那樣設置/獲取它們。如果我錯了,請隨時糾正我。
據我了解,從 DependencyObject 派生的所有 WPF 控制項(如 TextBlock、Button 等)也將包含依賴屬性來儲存其值,而不是使用 CLR 屬性。這具有在使用動畫的情況下覆蓋局部值的優點,或者如果根本沒有設置局部值則繼承值等。
我現在正在嘗試提出一些範例來創建和使用我自己的 dp。
- 是否可以在現有的 WPF 控制項上創建我自己的依賴屬性?假設我想要 WPF Textblock 類上的整數類型的依賴屬性?或者我是否必須創建一個從 TextBlockBase 派生的新類才能在上面創建我的依賴屬性?
2)在任何一種情況下,假設我在 WPF 文本塊類上創建了一個依賴屬性。現在我想通過將標籤的內容綁定到 TextBlock 的依賴屬性來利用它。這樣標籤將始終顯示 TextBlock dp 的實際值,無論它是繼承的還是本地設置的。
希望有人可以通過這兩個範例幫助我…非常感謝,凱夫
您可以使用附加屬性。
定義您的屬性 MyInt:
namespace WpfApplication5 { public class MyProperties { public static readonly System.Windows.DependencyProperty MyIntProperty; static MyProperties() { MyIntProperty = System.Windows.DependencyProperty.RegisterAttached( "MyInt", typeof(int), typeof(MyProperties)); } public static void SetMyInt(System.Windows.UIElement element, int value) { element.SetValue(MyIntProperty, value); } public static int GetMyInt(System.Windows.UIElement element) { return (int)element.GetValue(MyIntProperty); } } }綁定標籤內容:
<Window x:Class="WpfApplication5.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication5" Title="Window1" Height="300" Width="300"> <Grid> <Label Margin="98,115,51,119" Content="{Binding Path=(local:MyProperties.MyInt), RelativeSource={x:Static RelativeSource.Self}}" local:MyProperties.MyInt="42"/> </Grid> </Window>