Skip to main content
 首页 » 编程设计

c#之无法获取窗口宽度

2024年02月20日13think

我有一个 WPF 窗口,我正在尝试获取 Width 属性。无论我尝试在何处显示代码,它总是以 NaN 形式返回。我在 Internet 上查找并读到我实际上应该使用 ActualWidth,但无论如何都会返回 0。

如何消除延迟并获得窗口宽度的实际值?

XAML:

<Window x:Name="TableWindow" x:Class="QueryBuilder.DatabaseTable" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        WindowStyle="None" Background="Transparent" SizeToContent="WidthAndHeight" ResizeMode="CanResize"> 
    <Grid> 
        <DockPanel> 
            <StackPanel Name="titleBar" DockPanel.Dock="Top" Height="28" FlowDirection="RightToLeft" Orientation="Horizontal" Background="AliceBlue"> 
                <Button x:Name="btnClose" Margin="0,0,5,0" Click="btnClose_Click"> 
                </Button> 
                <Button> 
                </Button> 
                <Button> 
                </Button> 
                <Button x:Name="btnAll">ALL</Button> 
                <Label Name="lblTableName" FontSize="15" Margin="50,0,0,0"></Label> 
            </StackPanel> 
            <StackPanel Orientation="Vertical" Name="spFields"> 
            </StackPanel> 
        </DockPanel> 
    </Grid> 
</Window> 

XAML.cs:

public DatabaseTableWindow(string tableName, DataTable fields, string primaryKey) 
        { 
            InitializeComponent(); 
            this.tableName = tableName; 
            this.fields = fields; 
            this.primaryKey = primaryKey; 
            lblTableName.Content = tableName; 
            double x = this.ActualWidth; 
        } 

请您参考如下方法:

是的,ActualWidth 您需要查找。但是窗口的构造函数不是获取它的正确位置,因为 window 尚未呈现。而是使用 Loaded 事件 -

public DatabaseTableWindow(string tableName, DataTable fields, string primaryKey) 
{ 
    InitializeComponent(); 
    this.tableName = tableName; 
    this.fields = fields; 
    this.primaryKey = primaryKey; 
    lblTableName.Content = tableName; 
    Loaded += new RoutedEventHandler(MainWindow_Loaded);         
} 
 
void MainWindow_Loaded(object sender, RoutedEventArgs e) 
{ 
    double x = this.ActualWidth; 
} 

编辑

代替 Loaded,尝试挂接到构造函数中的 ContentRendered 事件 -

this.ContentRendered += new EventHandler(MainWindow_ContentRendered); 
 
void MainWindow_ContentRendered(object sender, EventArgs e) 
{ 
   double x = this.ActualWidth; 
}