簡體   English   中英

在WPF中動態更新StackPanel不能反映UI中的更改

[英]Updating a stackpanel in wpf dynamically doesn't reflect changes in UI

xaml中的Stackpanel:

 <StackPanel HorizontalAlignment="Right" Width="150" Height="280" Name="MyPanel">
            <TextBox HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="97"/>
  </StackPanel>

然后我將一些孩子添加到該堆棧面板中,例如:

MyPanel.Children.Add(new Rectangle { Fill = new SolidColorBrush(Colors.Chartreuse) }, Width=15, Height=15);

我還從后面的代碼中調用UpdateLayout

MyPanel.UpdateLayout();

但是布局保持不變,只有一個文本框。 我還嘗試過事先清理孩子,但效果不佳。

<Window x:Class="Demo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="650" Width="500"
        xmlns:local="clr-namespace:Demo">

    <Grid>
           <StackPanel Name="MyPanel" />
    </Grid>
</Window>

MainWindow.cs

namespace Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {            
        public MainWindow()
        {            
            InitializeComponent();
            for (var i = 0; i < 5; i++)
            {
                MyPanel.Children.Add(new Rectangle
                {
                    Width = 100,
                    Height = 20,
                    StrokeThickness = 1,
                    Stroke = new SolidColorBrush(Colors.Black),
                    Margin = new Thickness(5)
                });
            }
        }              
    }
}

我會回避代碼隱藏邏輯。

如果您在XAML中創建了一個矩形作為DataTemplate,然后依靠面板的ItemsSource屬性而不是添加矩形怎么辦?

通過DataBinding,您的數據模板將自動為您映射。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM