【问题标题】:Programmatically add control to Grid RowDefition in WPF 4.5以编程方式将控件添加到 WPF 4.5 中的 Grid RowDefition
【发布时间】:2012-09-10 05:22:44
【问题描述】:

我已经浏览了这个网站(以及许多其他网站),试图弄清楚发生了什么以及为什么它不起作用。我正在运行 VS2012 并创建了一个 WPF C# 应用程序(目标 .NET 4.5)。我是 WPF 新手,已经花了很多年编写 Windows 窗体应用程序的代码,但我决定冒险一试,到目前为止我很喜欢 XAML。

最终我想: 1)在我的网格中删除特定行(RowDefinition)中的用户控件 2) 在该特定行中放置另一个用户控件

但是我似乎无法放置一个简单的按钮控件。我想要做的是在第 4 行放置一个按钮(3 个零索引)。这是我的 XAML:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Custom="http://schemas.microsoft.com/winfx/2006/xaml/presentation/ribbon"
x:Class="TestApp2_WindowsClient.MainWindow"
Title="Test App 2" Height="700" Width="1000" MinHeight="700" MinWidth="1000" MaxHeight="700" MaxWidth="1000" FontSize="12" FontFamily="Segoe UI Semibold">
<Grid VerticalAlignment="Top" Name="gridMain">
    <Grid.RowDefinitions>
        <RowDefinition Height="60"/>
        <RowDefinition Height="152"/>
        <RowDefinition Height="240"/>
        <RowDefinition Height="60"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0"/>
    </Grid.ColumnDefinitions>

<StackPanel Name="stackButtons1" HorizontalAlignment="Left" Height="50" Margin="4,4,-310,4" Grid.Row="0" VerticalAlignment="Top" Width="300" Orientation="Horizontal" >
        <Button Content="Show Bookings" Height="24" Margin="4,0,0,0" Click="Button_Click_1" />
        <Button Content="Show Radio Buttons" Height="24" Margin="4,0,0,0" Click="Button_Click_2" />
    </StackPanel>

</Grid>
</Window>

按钮代码(堆栈面板中的第一个按钮)是:

Button MyControl = new Button();
MyControl.Content = "Test Button!";

Grid.SetRow(MyControl, 3); 
Grid.SetColumn(MyControl, 0); 
gridMain.Children.Add(MyControl); 

我可以看到(在我的手表中)gridMain.Children 计数值在我每次单击第一个按钮时都会增加,但屏幕上什么都没有显示。

这可能真的很愚蠢,但是几个小时的搜索和尝试一堆不同的代码并没有帮助。

提前致谢!

【问题讨论】:

  • 虽然与问题的答案无关,但这个问题确实解决了我遇到的问题(我一直在寻找 Grid.SetRow、Grid.SetColumn 和.Children.Add)。谢谢!

标签: c# .net wpf xaml .net-4.5


【解决方案1】:
<ColumnDefinition Width="0"/>

如果你增加宽度,也许你可以看到按钮。

【讨论】:

  • 值得注意的是,这些问题通常可以通过使用 Snoop 来诊断
猜你喜欢
  • 2011-02-18
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2018-10-30
  • 2016-02-12
  • 2010-10-14
  • 2010-10-16
相关资源
最近更新 更多