在WPF中有许多时候绑定到同一个对象上,因此就有一个隐式的数据源DataContext,有时把一个父控件直接设置成DataContext,当一个控件没有显示源对象时,WPF会遍历整个逻辑树,找到一个非空的Datacontext属性绑定上去。

  还有在一些情况下可以通过Tag来绑定一些东西,也可以把一些属性绑定到Tag上面去。下面有一个最简单的例子我把Context和Tag都写在了里面:

View Code
    <Window.Resources>
        <SolidColorBrush x:Key="myBrush" Color="Gold" />
    </Window.Resources>
    <Grid DataContext="{StaticResource myBrush}">
        <StackPanel>
            <Label x:Name="label" Background="{Binding}" Height="30"/>
            <TextBox Text="test1" Tag="{Binding ElementName=TxtBx2, Path=DataContext}" x:Name="TxtBx1"/>
            <TextBox Text="test2" x:Name="TxtBx2"/>
            <TextBox Text="{Binding ElementName=TxtBx1,Path=Tag}" x:Name="TxtBx3" />
        </StackPanel>
    </Grid>

  然后如果需哟通过绑定一些ListBox或ComboBox的选中项的话则需要使用这种类型的绑定:

<Button Tag="{Binding SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"/>

同时还需要注意的是:采用binding形式的tag只能在OnLoad时获取,如果tag为常量,则在ApplyTemplate时获取。

相关文章:

  • 2022-12-23
  • 2021-06-10
  • 2022-12-23
  • 2022-01-03
  • 2021-08-18
  • 2021-10-18
  • 2021-06-27
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-04
相关资源
相似解决方案