public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Button button1 = new Button();
Point tPosition = Mouse.GetPosition(this);
button1.Margin = new Thickness(tPosition.X,tPosition.Y,0,0) ;
button1.Width = 75;
this.AddChild(button1);
}
}
我认为代码非常明显,我在stackoverflow中使用了其他线程中批准的代码,它没有给出任何错误,但它也没有显示,是吗需要刷新窗口?怎么样?
按要求,XAML
<Window x:Class="Ampeldingensthingy.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid MouseLeftButtonDown="Grid_MouseLeftButtonDown" Name="hans">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="398*" />
<ColumnDefinition Width="105*" />
</Grid.ColumnDefinitions>
</Grid>
</Window>
答案 0 :(得分:0)
窗口只能有一个孩子,我想你已经有一个Grid订阅的MouseButtonDown。为该网格命名,然后替换
this.AddChild(按钮1);
与
grid.Children.Add(button1);
这里grid是Grid的名称。
答案 1 :(得分:0)
public partial class MainWindow : Window
{
public StackPanel SPanel{get;set;}
public MainWindow()
{
InitializeComponent();
SPanel = new StackPanel { Orientation = Orientation.Vertical };
}
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Button button1 = new Button();
Point tPosition = Mouse.GetPosition(this);
button1.Margin = new Thickness(tPosition.X,tPosition.Y,0,0) ;
button1.Width = 75;
SPanel.Children.Add(button1);
window.Content = SPanel;
}
}
尝试用画布做同样的事情。按钮将在您给出的位置弹出。
答案 2 :(得分:0)
对象&#34;这个&#34;这里描述了Window对象。 ContentControl的内容必须是单个元素。因此追加按钮是&#34; button1&#34;在父网格内。例如
private void Button_Click(object sender, RoutedEventArgs e)
{
Button button1 = new Button();
Point tPosition = Mouse.GetPosition(this);
button1.Margin = new Thickness(tPosition.X, tPosition.Y, 0, 0);
button1.Width = 75;
MainGrid.Children.Add(button1);
}
在你的Xaml中
<Grid x:Name="MainGrid">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Click="Button_Click" Content="click" Grid.Row="1"/>
</Grid>