如何获取XAML中定义的WrapPanel的维度

时间:2014-01-08 13:11:00

标签: c# .net wpf xaml wrappanel

我在XAML中定义了WrapPanel

<ScrollViewer Grid.Column="1" Grid.Row="2">
            <WrapPanel x:Name="VideoPanel" >
  </WrapPanel>
        </ScrollViewer>

然后当我访问WrapPanel

.cs的大小时
  Console.WriteLine(VideoPanel.ActualWidth + " x " + VideoPanel.ActualHeight);
        Console.WriteLine(VideoPanel.Width + " x " + VideoPanel.Height);

我得到了输出:

   0 x 0
0 x 0
is not a number x is not a number

如何获得实际尺寸?

完整的XAML:

<Window x:Class="HomeSecurity.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:HomeSecurity" 
        Title="MainWindow" WindowState="Maximized">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*" />
            <RowDefinition Height="9*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="8*" />
        </Grid.ColumnDefinitions>
        <ScrollViewer Grid.Column="1" Grid.Row="2">
            <WrapPanel x:Name="VideoPanel" >


            </WrapPanel>
        </ScrollViewer>
    </Grid>

</Window>

完整代码:

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {


        public MainWindow() {
            InitializeComponent();
            createGUI();
        }

        private void createGUI() {
            AddVideoStream("192.168.0.3");
        }

        private void AddVideoStream(String sourceIP) {

            Console.WriteLine(VideoPanel.ActualWidth + " x " + VideoPanel.ActualHeight);
            Console.WriteLine(VideoPanel.Width + " x " + VideoPanel.Height);

        }
    }

2 个答案:

答案 0 :(得分:1)

要获得实际尺寸,您应使用ActualWidth的{​​{1}}和ActualHeight属性,但不要使用FrameworkElement.Loaded事件中的{{3}}事件:

FrameworkElement

并在代码中

<Window x:Class="HomeSecurity.MainWindow" ... Loaded="Window_Loaded"> 

答案 1 :(得分:0)

试试这个

 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="1*" />
        <RowDefinition x:Name="Row"  Height="9*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="Column" Width="2*" />
        <ColumnDefinition  Width="8*" />
    </Grid.ColumnDefinitions>

    <!--Used for calculating height and width-->
    <Grid x:Name="Dimesiongrid" Grid.Column="1" Grid.Row="2"></Grid>

    <ScrollViewer Grid.Column="1" Grid.Row="2">
        <WrapPanel x:Name="VideoPanel" />
    </ScrollViewer>
</Grid>

并在代码后面

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        VideoPanel.Height = Dimesiongrid.ActualHeight;
        VideoPanel.Width = Dimesiongrid.ActualWidth;
    }

此高度和宽度可用于计算