<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)
{ }
}
我的鼠標懸停在列表框,按預期的方式顯示的按鈕。如果鼠標移動到右側列表框下方,則按鈕消失。爲什麼IsMouseOver在那裏是假的?內層StackPanel的Visibility屬性從Collapsed變爲Visible時,外層StackPanel的高度不應該增加嗎?
這裏的項目,如果你想用它玩:http://dl.dropbox.com/u/4220513/WpfApplication1.zip