WPF:
<Window x:Class="WpfApplication1.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>
<local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"
True="Visible"
False="Collapsed" />
</Window.Resources>
<Canvas>
<StackPanel Canvas.Left="100" Canvas.Top="100" Width="200" Height="100">
<ListBox>
<ListBoxItem>one</ListBoxItem>
<ListBoxItem>two</ListBoxItem>
<ListBoxItem>three</ListBoxItem>
</ListBox>
<StackPanel Orientation="Horizontal"
Visibility="{Binding
RelativeSource={RelativeSource AncestorType={x:Type StackPanel}},
Path=IsMouseOver,
Converter={StaticResource BooleanToVisibilityConverter}}">
<Button>one</Button>
<Button>two</Button>
<Button>three</Button>
</StackPanel>
</StackPanel>
</Canvas>
</Window>
代码:
public abstract class BooleanConverter<T> : IValueConverter
{
public BooleanConverter(T trueValue, T falseValue)
{
True = trueValue;
False = falseValue;
}
public T True { get; set; }
public T False { get; set; }
public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is bool && ((bool)value) ? True : False;
}
public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is T && EqualityComparer<T>.Default.Equals((T)value, True);
}
}
public class BooleanToVisibilityConverter : BooleanConverter<Visibility>
{
public BooleanToVisibilityConverter()
: base(Visibility.Visible, Visibility.Collapsed)
{ }
}
我的鼠标悬停在ListBox上,按钮按预期显示。如果鼠标移动到右侧的ListBox下方,则按钮消失。为什么IsMouseOver在那边是假的?当内部StackPanel的Visibility属性从Collapsed更改为Visible时,外部StackPanel的高度是否应该增加?
如果您想使用它,可以使用以下项目:http://dl.dropbox.com/u/4220513/WpfApplication1.zip
答案 0 :(得分:3)
您需要将StackPanel(外部)的背景设置为Transparent以检测鼠标悬停。如果背景在样本中为null,则命中测试将失败。
答案 1 :(得分:1)
使用StackPanel
的背景,例如<StackPanel Background="Transparent">
...