Setter.Property 屬性

定義

取得或設定要套用 Value 的屬性。

public:
 property DependencyProperty ^ Property { DependencyProperty ^ get(); void set(DependencyProperty ^ value); };
DependencyProperty Property();

void Property(DependencyProperty value);
public DependencyProperty Property { get; set; }
var dependencyProperty = setter.property;
setter.property = dependencyProperty;
Public Property Property As DependencyProperty
<Setter Property="propertyName"/>

屬性值

將套用ValueDependencyProperty。 預設值為 null

範例

此範例示範如何在 TextBlock 元素的樣式中使用 Setter 語句。

<StackPanel>
    <StackPanel.Resources>
        <!-- Create a Style for a TextBlock to specify that the
             Foreground equals Navy, FontSize equals 14, and
             VerticalAlignment equals Bottom. -->
        <Style TargetType="TextBlock" x:Key="TextBlockStyle">
            <Setter Property="Foreground" Value="Navy"/>
            <Setter Property="FontSize" Value="14"/>
            <Setter Property="VerticalAlignment" Value="Bottom"/>
        </Style>
    </StackPanel.Resources>

    <!-- Apply the TextBlockStyle to 2 different TextBlocks. -->
    <TextBlock Style="{StaticResource TextBlockStyle}" Text="Hello"/>
    <TextBlock Style="{StaticResource TextBlockStyle}" Text="World"/>
</StackPanel>

您也可以在 AttachedPropertyProvider中指定附加屬性名稱,將 setter 套用至附加屬性值。PropertyName 表單。 例如,若要針對附加屬性Canvas.Left使用Setter,請使用這個 XAML。

<Setter Property="Canvas.Left" Value="100"/>

備註

您必須在Setter上同時指定 Property 和Value屬性。 否則會擲回例外狀況 (剖析例外狀況或執行時間錯誤,視 Setter 是在 XAML 中建立或修改程式碼) 而定。

如果您使用程式碼存取Setter實例,如果父Style上的IsSealed屬性值為 true,就無法變更Setter實例的任何屬性值。 這也會由個別Setter上的IsSealed屬性報告。 當執行時間將樣式套用至 UI 元素並在 UI 中顯示樣式時,系統會將這些屬性設定為 true 。 嘗試變更密封 的 Setter 會擲回執行階段錯誤。

您可以使用 Setter 來設定附加屬性的樣式。 在此情況下,相依性屬性名稱是 XAML 中的限定名稱,也會命名附加屬性的定義型別。 例如, <Setter Property="AutomationProperties.LiveSetting" Value="Polite" /> 可用來設定任何控制項或 UI 元素之樣式內的 AutomationProperties.LiveSetting 附加屬性值。

注意

XAML 剖析器也接受包含限定類別的相依性屬性名稱。 例如,剖析器會將 「Button.Background」 或 「Control.Background」 解譯為Button樣式中Background屬性的參考。 不過,不需要依類別限定,而且可能會導致混淆的標記。 如果您要從其他平臺移轉 XAML,可能會遇到或使用限定的屬性名稱使用方式。

識別相依性屬性

如前所述,如果有問題的屬性是相依性屬性,您只能使用 Setter 來透過樣式調整屬性。 在套用樣式的案例中,UI 屬性幾乎一律會由Windows 執行階段實作為相依性屬性,而且不是 UI 元素上相依性屬性的可設定屬性相當罕見。 如果您想要確認Windows 執行階段屬性是否為相依性屬性,請檢查成員清單以取得原本定義屬性的類型。 如果屬性事實上是相依性屬性,相依性屬性識別碼也會存在於該類別上,而且該識別碼的名稱與屬性本身相同,但加上尾碼 屬性 。 此相依性屬性識別碼是靜態唯讀屬性,可透過程式碼在某些相依性屬性案例中很有用。 例如,您可以使用程式碼中的這類識別碼值來調整現有的 Setter.Property 值,前提是父樣式尚未密封。

針對自訂屬性使用 Setter

針對您自己的自訂屬性,如果您想要支援樣式,以及資料系結或動畫等其他案例,您應該將 屬性宣告為相依性屬性。 如果您這麼做,也支援使用參考自訂類型之 TargetType的任何Style樣式來設定自訂屬性。 如需詳細資訊,請參閱 自訂相依性屬性TargetType

適用於