2010-10-18 165 views
5

有没有可能在ListBox中的项目旁边放置弹出窗口? 我使用MVVM,列表绑定到元素,并且对于一些选择的元素,我想在该项旁边显示弹出。Wpf Popup placement

我有元素列表,我希望在点击指定列表元素时显示弹出窗口,但弹出窗口应显示在选定列表项旁边。

我想是这样的(它不工作):

<Popup IsOpen="{Binding Path=ShowPopup}" PlacementTarget="{Binding ElementName=List1, Path=SelectedItem}" Placement="Center"> 
     <TextBox Background="Red" Height="120" Text="Aaaaaa FUUUUUUUUUUUUU....."></TextBox> 
    </Popup> 

我不想背后使用代码,只有XAML

回答

1

既然你希望在项目显示弹出被点击,这会为你工作:

<Popup IsOpen="{Binding Path=ShowPopup}" Placement="Mouse"> 
    <TextBox Background="Red" Height="120" Text="Aaaaaa FUUUUUUUUUUUUU....."></TextBox> 
</Popup> 
2

你的例子不起作用的原因仅仅是因为你将展示位置目标绑定到非ui对象。

PlacementTarget="{Binding ElementName=List1, Path=SelectedItem}" 

的SelectedItem在这种情况下,可能是代表你的列表中的项目模型/视图模型,为此是不是PlacementTarget属性的正确用法。

您需要的是将PlacementTarget设置为ItemContainer(Dr. WPF explains),如果没有“some”代码的帮助,这是不可能的。

现在你已经知道这个问题了,有几种方法可以使你的代码工作,所以我会把它留给你。

6

这将弹出放置到所选择的一个ListBoxItem

alt text

<Window.Resources> 
    <SolidColorBrush x:Key="SelectedBackgroundBrush" Color="#DDD" /> 
    <SolidColorBrush x:Key="DisabledForegroundBrush" Color="#888" /> 

    <ControlTemplate x:Key="PopupListBoxItemTemplate" TargetType="ListBoxItem"> 
     <Border Name="Border" Padding="2" SnapsToDevicePixels="true"> 
      <Grid> 
       <Popup Name="c_popup" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" Placement="Right" > 
        <Border BorderBrush="Black" BorderThickness="1" CornerRadius="2.5"> 
         <TextBlock Background="Wheat" Foreground="Black" Text="Aaaaaa FUUUUUUUUUUUUU....."/> 
        </Border> 
       </Popup> 
       <ContentPresenter /> 
      </Grid> 
     </Border> 
     <ControlTemplate.Triggers> 
      <Trigger Property="IsSelected" Value="true"> 
       <Setter TargetName="Border" Property="Background" Value="{StaticResource SelectedBackgroundBrush}"/> 
       <Setter TargetName="c_popup" Property="IsOpen" Value="True"/> 
      </Trigger> 
      <Trigger Property="IsEnabled" Value="false"> 
       <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/> 
      </Trigger> 
     </ControlTemplate.Triggers> 
    </ControlTemplate> 
</Window.Resources> 
<Grid> 
    <ListBox Name="listBox" 
      ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}"> 
     <ListBox.ItemContainerStyle> 
      <Style TargetType="{x:Type ListBoxItem}"> 
       <Setter Property="Template" Value="{StaticResource PopupListBoxItemTemplate}" /> 
      </Style> 
     </ListBox.ItemContainerStyle> 
    </ListBox> 
</Grid> 
+1

优秀溶液的右侧,但我发现一个小错误。为了得到这个工作,我必须将Setter从{StaticResource ListBoxItemTemplate}更改为StaticResource PopupListBoxItemTemplate}。 – Caustix 2017-10-29 17:23:24