【问题标题】:DataTrigger not working (LineCount always -1)DataTrigger 不工作(LineCount 始终为 -1)
【发布时间】:2013-11-01 13:20:30
【问题描述】:

下面的数据触发器不工作。知道为什么不?
我检查了后面的代码,两种情况下的 LineCount 分别为 1 和 4。
但是当我将值更改为“-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>

【问题讨论】:

  • 我刚刚在 MSDN TextBox.LineCount 属性中看到:不能在 xaml(框架 3.5)中设置此属性。
  • 在代码中通过this.TextInfo.TextChanged += TextInfo_TextChanged; 工作,我想这比创建附加的依赖属性要容易一些。

标签: wpf datatrigger


【解决方案1】:

查看 MSDN 上的 TextBox.LineCount Property 页面,我们可以看到它不是 DependencyProperty。此外,由于TextBox类没有实现INotifyPropertyChanged接口,我只能想象这个属性的值永远不会在Binding中为你更新,只能在代码中使用。

我可以看到您使用此属性的唯一方法是您创建一个Attached Property 来访问它并公开更新的值。

【讨论】:

  • 你怎么在 MSDN 中看到它不是 DependencyProperty?
  • 当属性是DependencyProperty时,MSDN上的属性页会有一个“依赖属性信息”部分...比较TextBox.LineCount属性页和TextBox.Text属性页。
  • Thyvm,我接受了 Kevin DeLorey 的回答,让他快速入门;)
  • 我的朋友一点问题都没有。
【解决方案2】:

TextBox 代码的快速反编译表明LineCount 不是DependencyProperty。因此,当值更新时,它不会更新您的触发器。

这是来自 C# 中 System.Windows.Controls.TextBox 类的 LineCount 属性。您可以在这里看到没有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 中的文本何时被修改,并给出当前行位置。您可以更改绑定以侦听附加属性。

【讨论】:

  • “文本框代码的快速反编译”——你是怎么做到的?
  • @Gerard 有几个应用程序可以让您反编译程序集。 dotPeek 是免费且相当不错的。希望对您有所帮助。
【解决方案3】:

你不需要ElementName,使用RelativeSource

<DataTrigger Binding="{Binding LineCount, RelativeSource={RelativeSource Self}}" Value="4">

【讨论】:

  • 这没什么区别,它也可以,但是 LineCount 总是-1。
【解决方案4】:

TextBoxLineCount 属性可用于检索TextBox 中的当前文本行数。如果文本换行为多行,则此属性将反映用户看到的可见换行数。

<TextBox x:Name="TextInfo" Text="Information" HorizontalAlignment="Stretch" Foreground="OrangeRed" **TextWrapping="Wrap"**>
    <TextBox.Style>
     ....
    </TextBox.Style>
</TextBox>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2014-03-04
    • 2016-07-15
    相关资源
    最近更新 更多