2010-10-15 65 views
7

我一直在閱讀Dependency屬性幾天,並理解它們如何檢索值,而不是像CLR屬性中那樣設置/獲取它們。如果我錯了,隨時糾正我。如何在現有的控件上創建一個Dependency屬性?

根據我的理解,從DependencyObject派生的所有WPF控件(如TextBlock,Button等)也將包含依賴屬性來存儲它們的值,而不是使用CLR屬性。這有利於在使用動畫時覆蓋本地值,或者在沒有設置本地值的情況下繼承值。

我現在試圖想出一些示例來創建和使用我自己的dp。

1)是否有可能在現有的WPF控件上創建自己的依賴屬性?假設我想在WPF Textblock類上使用整數類型的依賴項屬性?或者我必須創建一個從TextBlockBase派生的新類,以便在那裏創建我的依賴屬性?

2)在這兩種情況下,假設我已經創建了WPF文本塊類的依賴項屬性。現在我想通過將標籤的內容綁定到TextBlock的依賴屬性來利用它。所以標籤總是會顯示TextBlock的dp的實際值,無論它是繼承還是本地設置。

希望有人能幫助我與這兩個例子...... 非常感謝, 卡瓦

回答

6

可以使用attached properties它。

定義你的財產敏:


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> 
+0

感謝,這也是一種很好的替代,這是我將很快試圖。 – Houman 2010-10-18 20:56:21

1

你不能添加到DependencyProperties現有的類型。雖然您可以使用AttachedProperty,但使用它的邏輯和派生新類型的邏輯完全不同。

在你的情況下,我會建議派生新的類型。主要是因爲你的邏輯與這種類型綁定。這是繼承的基礎,並且不與依賴屬性綁定。

在AttachedProperty的情況下,你只是給另一個對象在不同的​​對象上的值的一致性。像Grid.Row這樣的東西給了它的孩子的網格粗糙以及它應該如何定位它。該屬性設置的對象不知道任何東西。

+0

謝謝。我爲什麼要永遠創建dp?我讀過一些人創造他們自己的。我想看一個例子,它是有道理的創建自己的DP ... – Houman 2010-10-18 20:55:44

0

這裏是關於運行元件的ovveride一個例子:

using System; 
using System.Windows; 
using System.Windows.Documents; 

namespace MyNameSpace.FlowDocumentBuilder 
{ 
    public class ModifiedRun : Run 
    { 
     static DateRun() 
     { 
      TextProperty.OverrideMetadata(typeof(DateRun),new FrameworkPropertyMetadata(string.Empty,FrameworkPropertyMetadataOptions.Inherits,null,CoerceValue)); 
     } 

     private static object CoerceValue(DependencyObject d, object basevalue) 
     { 
      return "AAAAAAAA"; 
     } 
    } 
} 

一個相應XAML是:

<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
         ColumnWidth="400" 
         FontSize="14" 
         FontFamily="Arial" 
xmlns:local="clr-namespace:MyNameSpace.FlowDocumentBuilder;assembly=MyNameSpace.FlowDocumentBuilder" 
> 

<Paragraph><local:ModifiedRun Text="BBBBBBBBBB"/></Paragraph> 

</FlowDocument> 
相關問題