1. 程式人生 > WINDOWS開發 >WPF學習之資料繫結

WPF學習之資料繫結

原文:WPF學習之資料繫結

技術分享圖片

<StackPanel Name="StackPanelOut">
    <StackPanel Name="StackPanelIn">
        <!--繫結元素-->
        <Slider Name="sliderFont" Maximum="40" Minimum="10" Value="20" TickPlacement="BottomRight"  TickFrequency="1" IsSnapToTickEnabled="True" Height="Auto" Margin="5" ></Slider>
        <!--將某一屬性繫結到上一個元素(ElementName),繫結值(Path),繫結模式(預設單向)-->
        <Label FontSize="
{Binding ElementName=sliderFont,Path=Value,Mode=TwoWay}" Content="{Binding ElementName=sliderFont,Path=Value}"></Label> <!--將某一屬性,繫結到非元素資源--> <Label Content="{Binding Source={x:Static SystemFonts.IconFontFamily},Path=Source}"/> <!--繫結到靜態資源--> <Label Content="
{Binding Source={StaticResource MyFont},Path=Source}"></Label> <!--繫結到自定義資源--> <Label> <!--繫結到父類的資料--> <Label.Content> <Binding Path="Title"> <!--繫結到父類的值--> <Binding.RelativeSource> <!--繫結模式,繫結的型別--> <RelativeSource Mode="
FindAncestor" AncestorType="{x:Type Window}"/> </Binding.RelativeSource> </Binding> </Label.Content> </Label> <!--針對上一個的簡寫,AncestorLevel在元素樹上向上查詢的等級--> <Label Content="{Binding Path=Name,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type StackPanel},AncestorLevel=2}}"/> <!--多元素,繫結同一資料時的處理(處理相同源)--> <Label Content="{Binding Source={x:Static SystemFonts.IconFontFamily},Path=Source}"/> <Label Content="{Binding Source={x:Static SystemFonts.IconFontFamily},Path=LineSpacing}"/> <Label Content="{Binding Source={x:Static SystemFonts.IconFontFamily},Path= FamilyTypefaces[0].Style}"/> <!--將上面繫結的資料 儲存在父級(也可以是更高的父級)的DataContext中--> <StackPanel DataContext="{x:Static SystemFonts.IconFontFamily}"> <!--空出Source,WPF會自動向上查詢父級中DataContext不為null的資料,並應用。如果找不到或者錯誤,則不顯示--> <Label Content="{Binding Path=Source}"/> <Label Content="{Binding Path=LineSpacing}"/> <Label Content="{Binding Path= FamilyTypefaces[0].Style}"/> </StackPanel> </StackPanel> </StackPanel>
技術分享圖片