我最近在堆栈溢出的一些帮助下解决了一个样式问题...(您可以在我的历史记录中看到问题/答案)
因此,我想出了以下样式来应用于特定的文本框。
<!--Expanding text box with the max width in the tag property-->
<!---->
<!--Will not work with password box!!-->
<Style TargetType="{x:Type TextBox}"
x:Key="ExpandingTextBoxMaxWidthInTag">
<Setter Property="OverridesDefaultStyle"
Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*">
<ColumnDefinition.MaxWidth>
<Binding Path="Tag"
RelativeSource="{RelativeSource TemplatedParent}">
</Binding>
</ColumnDefinition.MaxWidth>
</ColumnDefinition>
<ColumnDefinition Width="0*" />
</Grid.ColumnDefinitions>
<TextBox>
<TextBox.Text>
<Binding Path="Text"
RelativeSource="{RelativeSource TemplatedParent}" />
</TextBox.Text>
<TextBox.MaxWidth>
<Binding Path="Tag"
RelativeSource="{RelativeSource TemplatedParent}" />
</TextBox.MaxWidth>
</TextBox>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
(代码清单1)
然后我将其应用到代码中的文本框,就像这样......
<TextBox Tag="150"
Text="{Binding Path=Username}"
Style="{StaticResource ExpandingTextBoxMaxWidthInTag}" />
(代码清单2)
我必须强调,正如所写的那样,这段代码可以按预期工作。当我将 UpdateSourceTrigger=PropertyChanged 添加到 Text 属性上的绑定时,就会出现问题...
<TextBox Tag="150"
Text="{Binding Path=Username, UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource ExpandingTextBoxMaxWidthInTag}" />
(代码清单3)
清单 3 中的代码有一个例外:更新源触发器没有正确触发。它不是在每次击键时触发(就像没有应用样式时一样),而是仅在失去焦点事件时触发(默认)。
我不能简单地在样式中显式应用“PropertyChanged”,因为我需要将样式应用到一堆对于更新源触发器有不同需求的文本框。
如何在 xaml 中获取指定的更新源触发器以过滤到我的样式?
您用您的样式覆盖了“Text”属性,因此也覆盖了“UpdateSourceTrigger=PropertyChanged”部分,不是吗?只需删除样式中的“文本”属性绑定,这应该可以正常工作。