Popup 中的 ListBox - 位置和绑定问题

ListBox within Popup - position and binding issue

以下是UI的代码和后面的代码。没有比这更多的代码了。

问题是

  1. ListBox 当我将值绑定到 ObservableCollection 有一些延迟时不可见。
  2. ListBox 不在弹出窗口的中心。可以在 Design Viewer 中看到。

我尝试将 ListBox 放在弹出窗口之外,效果很好。我的需要是在弹出窗口中放置列表框。

MainWindow.xaml

<Window x:Class="WPFTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFTest"
        mc:Ignorable="d"
        Title="TestWPF" MinHeight="500" MinWidth="600" 
        WindowStyle="SingleBorderWindow" WindowStartupLocation="CenterScreen">
    <Grid x:Name="mainContainer">

        <Popup x:Name="popup" IsOpen="False" Margin="10" PlacementTarget="{Binding ElementName=mainContainer}"
               Placement="Center" Height="300" Width="300">
            <ListBox ItemsSource="{Binding InstallationSummary}"> 
                <ListBox.ItemContainerStyle>
                    <Style TargetType="ListBoxItem">
                        <Setter Property="IsEnabled" Value="False"/>
                        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                    </Style>
                </ListBox.ItemContainerStyle>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Border BorderThickness="0,0,0,1" 
                            Margin="5" Padding="2">
                            <TextBlock Text="{Binding}"
                                       TextWrapping="Wrap" Foreground="Black"/>
                        </Border>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Popup>
    </Grid>
</Window>

MainWindow.xaml.cs

using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;

namespace WPFTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ObservableCollection<string> InstallationSummary;

        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += MainWindow_Loaded;

            InstallationSummary = new ObservableCollection<string>();

            this.DataContext = this;
        }

        async private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            popup.IsOpen = true;

            for (int i = 0; i < 25; i++)
            {
                await Task.Delay(1000);

                App.Current.Dispatcher.Invoke(() =>
                {
                    InstallationSummary.Add("New Item-" + i);
                });
            }
        }
    }
}

尝试转换你的私有变量 ObservableCollection 安装总结 像这样 public 属性

public ObservableCollection<string> InstallationSummary{ get set};

应该可以正常工作..