使用TemplateBinding更新源代码

时间:2010-05-12 10:46:02

标签: wpf data-binding templatebinding

我将这种风格用于所有标签

    <Style TargetType="Label" x:Key="LabelStyle">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Label">
                    <StackPanel Orientation="Horizontal"  >
                        <TextBox Loaded="MyTextBlock_Loaded" x:Name="EditControl" Visibility="Collapsed" Text="{TemplateBinding Tag}" />
                        <Label Content="{TemplateBinding Content}" Grid.Column="1" Grid.Row="1">
                        </Label>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

和我的样本标签

<Label Grid.Column="0" Grid.Row="0" Content="Photo" Style="{StaticResource LabelStyle}" Tag="{Binding fieldsCode.firstName, UpdateSourceTrigger=PropertyChanged}"/>

但我觉得TemplateBiding不支持更新属性。如何解决这个问题

2 个答案:

答案 0 :(得分:27)

尝试使用双向绑定

Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Tag, Mode=TwoWay}"

答案 1 :(得分:1)

如果您希望从ControlTemplate中单向绑定到其模板化父级的属性,请使用{TemplateBinding}。对于所有其他场景,请改为使用{Binding}:

<TextBox Loaded="MyTextBlock_Loaded" x:Name="EditControl" Visibility="Collapsed" Text="{Binding Tag, Mode=TwoWay}" />