我試圖創建自定義RoutedEvent
以便在TextBlock
的Text
屬性更改時觸發動畫。我的班級繼承了TextBlock
班,並且我影響了Text
特性。我正在使用Button
以更改Text
屬性的某些其他值。我的代碼不會產生任何錯誤,但它不會執行任何操作。我確信問題出在TextChanged
事件上,因爲當我將其替換爲MouseEnter
事件時,一切正常。我的自定義事件不會產生任何東西
Public Class MyCustomTextBlock
Inherits TextBlock
Public Shared ReadOnly TextChangedEvent As RoutedEvent = EventManager.RegisterRoutedEvent("TextChanged", _
RoutingStrategy.Bubble, GetType(RoutedEventArgs), GetType(MyCustomTextBlock))
Public Custom Event TextChanged As RoutedEventHandler
AddHandler(ByVal value As RoutedEventHandler)
Me.AddHandler(TextChangedEvent, value)
End AddHandler
RemoveHandler(ByVal value As RoutedEventHandler)
Me.RemoveHandler(TextChangedEvent, value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
Me.RaiseEvent(e)
End RaiseEvent
End Event
Public Shared Shadows TextProperty As DependencyProperty =
DependencyProperty.Register("Text", GetType(String), GetType(MyCustomTextBlock),
New FrameworkPropertyMetadata(String.Empty,
New PropertyChangedCallback(AddressOf TextPropertyChanged)))
Private Shared Sub TextPropertyChanged(ByVal sender As Object, ByVal e As DependencyPropertyChangedEventArgs)
DirectCast(sender, MyCustomTextBlock).RaiseEvent(New RoutedEventArgs(MyCustomTextBlock.TextChangedEvent))
End Sub
End Class
XAML
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="local:MyCustomTextBlock">
<Style.Triggers>
<EventTrigger RoutedEvent="local:MyCustomTextBlock.TextChanged">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="FontSize" To="30" Duration="0:0:1" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<local:MyCustomTextBlock x:Name="Textblock1" Text="xxxxxxxxx" Background="Yellow" Width="100" Height="25" />
<Button Content="Change Text" Height="23" HorizontalAlignment="Left" Margin="217,218,0,0" Name="Button1" VerticalAlignment="Top" Width="75" />
</Grid>
Class Main Window
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.Windows.RoutedEventArgs) Handles Button1.Click
Textblock1.Text = "apollon"
End Sub
End Class
感謝您的迴應!我使用文本塊而不是文本框...所以在基類中沒有TextChanged事件。 – apollon 2013-05-09 18:23:31
所以我試過你的代碼,它工作正常。感謝很多優秀的職位! – apollon 2013-05-09 21:22:52