【发布时间】:2015-11-06 15:45:43
【问题描述】:
我在ContentControl 中加载了一个TextBlock,并在TextBlock 的Inlines 集合中添加了一个Hyperlink 作为对象。
如果我订阅了设置ContentControl.Foreground 属性的ContentControl.PreviewMouseUp 事件的处理程序,则在第一次单击链接时不会引发RequestNavigate 和Click 事件。如果再次单击该链接,则会引发事件。
如果没有订阅事件,或者处理程序什么都不做,一切正常。
初始化代码(在窗口构造函数中,在InitializeComponent()之后):
var run = new Run("Google");
Hyperlink hyperlink = new Hyperlink(run);
hyperlink.Click += hyperlink_Click;
hyperlink.RequestNavigate += hyper_RequestNavigate;
hyperlink.NavigateUri = new Uri("http://www.google.com");
textBlock.Inlines.Clear();
textBlock.Inlines.Add(hyperlink);
事件处理程序如下:
private void hyper_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
System.Diagnostics.Process.Start(e.Uri.ToString());
}
void contentControl_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
contentControl.Foreground = Brushes.Green;
}
void hyperlink_Click(object sender, RoutedEventArgs e)
{
}
XAML如下:
<Grid>
<ContentControl Name="contentControl">
<TextBlock Name="textBlock"
Width="200"
Height="30" />
</ContentControl>
</Grid>
注意:如果 PreviewMouseUp 处理程序发生更改,使其始终更改颜色(例如,创建一个在两种不同颜色之间进行选择并在每次处理程序时切换的 bool被调用),则永远不会引发事件。例如:
private bool _toggle;
void contentControl_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
contentControl.Foreground = _toggle ? Brushes.Red : Brushes.Green;
_toggle = !_toggle;
}
有什么方法可以让PreviewMouseUp 处理程序设置颜色,但在第一次单击链接时仍会引发RequestNavigate 和Click 事件?
【问题讨论】: