2011-07-06 10 views
4

WPF:IsMouseOver、可視性、およびコントロール寸法

<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はfalseですか?内側のStackPanelのVisibilityプロパティがCollapsedからVisibleに変わったときに、外側のStackPanelの高さを上げてはいけませんか?あなたはそれを再生したい場合は

はここでプロジェクトだ:http://dl.dropbox.com/u/4220513/WpfApplication1.zip

enter image description here

答えて

3

あなたは、マウスの上に検出するために、透明にStackPanelの(外1)の背景を設定する必要があります。サンプルのように背景がヌルの場合、ヒットテストは失敗します。

1

StackPanelの背景を使用してください。<StackPanel Background="Transparent"> ...