下面的数据触发器不起作用。知道为什么不呢?
我在后面检查了代码,两种情况下的LineCount分别是1
但当我将值更改为“-1”时,触发器正在工作
那么为什么LineCount总是-1?
<TextBox x:Name="TextInfo" TextWrapping="Wrap" Text="Information" HorizontalAlignment="Stretch" Foreground="OrangeRed">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding LineCount, ElementName=TextInfo}" Value="4">
<Setter Property="Background" Value="Green" />
</DataTrigger>
<DataTrigger Binding="{Binding LineCount, ElementName=TextInfo}" Value="1">
<Setter Property="Background" Value="PowderBlue" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
答案 0 :(得分:2)
查看MSDN上的TextBox.LineCount
Property页面,我们可以看到不一个DependencyProperty
。此外,由于TextBox
类没有实现INotifyPropertyChanged
接口,我只能想象这个属性的值永远不会在Binding
中为您更新,并且只能在代码中使用
我可以看到您使用此属性的唯一方法是创建Attached Property
来访问它并公开更新后的值。
答案 1 :(得分:1)
TextBox
代码的快速反编译显示LineCount
不是DependencyProperty
。因此,当值更新时,它不会更新您的触发器。
这是来自C#中LineCount
类的System.Windows.Controls.TextBox
属性。您可以在此处看到没有DependencyProperty
支持该属性。
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int LineCount
{
get
{
if (this.RenderScope == null)
return -1;
else
return this.GetLineIndexFromCharacterIndex(this.TextContainer.SymbolCount) + 1;
}
}
this question作为创建附加属性的合适解决方案的答案,该附加属性将观察TextBox
中的文本何时被修改,并给出当前行位置。您可以更改绑定以侦听附加属性。
答案 2 :(得分:0)
您不需要ElementName
,请使用RelativeSource
:
<DataTrigger Binding="{Binding LineCount, RelativeSource={RelativeSource Self}}" Value="4">
答案 3 :(得分:0)
TextBox 的 LineCount 属性可用于检索 TextBox 中当前的文本行数。如果文本包装到多行,则此属性将反映用户看到的可见包裹行数。
<TextBox x:Name="TextInfo" Text="Information" HorizontalAlignment="Stretch" Foreground="OrangeRed" **TextWrapping="Wrap"**>
<TextBox.Style>
....
</TextBox.Style>
</TextBox>