2010-10-18 85 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