2013-11-01 29 views
0

下面的datatrigger不起作用。任何想法爲什麼不呢?
我檢查後面的代碼,在兩種情況下LineCount分別是1.
但是,當我將值更改爲「-1」觸發器正在工作。
那麼爲什麼LineCount總是-1?DataTrigger不能正常工作(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

我剛剛在MSDN中看到TextBox.LineCount屬性:你不能在xaml(framework 3.5)中設置這個屬性。 – Gerard

+0

在代碼中通過'this.TextInfo.TextChanged + = TextInfo_TextChanged;'它的工作原理,我想這比創建附加的依賴屬性要容易一些。 – Gerard

回答

1

TextBox代碼的快速反編譯顯示LineCount不是DependencyProperty。所以當這個值更新時它不會更新你的觸發器。

這是LineCount財產來自System.Windows.Controls.TextBox類在C#中。你可以看到這裏沒有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文本被修改,並給當前行位置體面溶液。您可以更改綁定以偵聽附加屬性。

+0

「TextBox代碼的快速反編譯」 - 你怎麼做? – Gerard

+0

@Gerard有幾個應用程序可以讓你反編譯程序集。 [dotPeek](http://www.jetbrains.com/decompiler/)是一款免費而且相當不錯的遊戲。希望能幫助到你。 – deloreyk

0

你不需要ElementName,使用RelativeSource

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

這沒什麼區別,它也可以工作,但是LineCount一直是-1。 – Gerard

0

一個文本框LineCount屬性可用於檢索在文本框文本行的當前數量。如果文字將換行爲多行,則此屬性將反映用戶看到的可見行數。

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

對不起,我有(編輯我的問題)。 – Gerard

2

縱觀TextBox.LineCount Property頁面上MSDN中,我們可以看到,它是不是一個DependencyProperty。此外,由於TextBox類沒有實現接口INotifyPropertyChanged,我只能想象這個屬性的值永遠不會在Binding中更新,只能在代碼中使用。

我可以看到你使用這個屬性的唯一方法是如果你創建一個Attached Property來訪問它並公開更新的值。

+0

您如何在MSDN中看到它不是DependencyProperty? – Gerard

+0

當一個屬性是'DependencyProperty'時,MSDN上的屬性頁將會有一個'Dependency Property Information'部分...將TextBox.LineCount屬性頁面與TextBox.Text屬性頁面進行比較。 – Sheridan

+1

Thyvm,我接受了Kevin DeLorey的回答,讓他快速入門;) – Gerard