所谓的潇洒

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

WPF知识点备忘录——元素绑定

1.元素绑定

<Slider Name="sliderFontSize" Margin="3" Value="10" />
<TextBlock Margin="10" Text="AAA" 
  FontSize
="{Binding ElementName=sliderFontSize,Path=Value,Mode=TwoWay,Delay=500,UpdateSourceTrigger=PropertyChaged}"/>

2.绑定模式

   Mode:OneWay、TwoWay、OneTime、OneWayToSource、Default

   绑定表达式只能用于依赖项属性,可以使用OneWayToSource来实现更新非依赖项属性的效果,例如

错误的绑定:            
  <TextBlock Name="textBlock_MyProp" Text="{Binding ElementName=textBlock_MyProp,Path=Text}"/>
   <TextBox Name="txtBox_MyProp"/>

正确写法:
   <TextBlock Name="textBlock_MyProp"/>
   <TextBox Text="{Binding ElementName=textBlock_MyProp,Path=Text,Mode=OneWayToSource}"/>

3.绑定更新

  更新触发UpdateSourceTrigger:

    PropertyChaged(大多数默认此)

    LoseFocus(TextBox.Text默认此)

    Explicit(除非调用BindingExpression.UpdateSource(),否则无法更新源)

    Default

 延迟更新:Delay=500

4.绑定到非元素对象

  Source

<Window.Resource>
    <FontFamiliy x:Key="CustomFont">Calibri</FontFamily>
</Window.Resource>

<TextBlock Text="{Binding Source={StaticResource CustomFont},Path=Source}"></TextBlock>

  RelativeSource

<TextBlock Text="{Binding Path=Title,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Window}}}" />

    Self:绑定到自身的另一个属性上

    FindAncestor:向父级方向找匹配属性

    PreviousData:绑定到数据绑定列表中的前一项,在列表项中会使用这种模式

    TemplateParent:绑定到应用模板的元素,只用于控件模板和数据模板内部

  DataContent    

        <StackPanel Grid.Row="4" Grid.Column="1" DataContext="{x:Static SystemFonts.IconFontFamily}">
            <TextBlock Text="{Binding Path=Source}"/>
            <TextBlock Text="{Binding Source={x:Static SystemFonts.IconFontFamily},Path=FamilyTypefaces[0]}"/>
            <TextBlock Text="{Binding Path=FamilyTypefaces.Count}"/>
            <TextBlock Text="{Binding ElementName=cb_1,Path=(Grid.Row)}"/>
        </StackPanel>

 

posted on   所谓的潇洒  阅读(88)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示