【问题标题】:C# WPF Can't click button after defining marginC# WPF 定义边距后无法单击按钮
【发布时间】:2017-03-07 07:02:19
【问题描述】:

我使用以下代码在我的 WPF 应用程序中创建了一个按钮:

Button EditButton = new Button();
EditButton.Margin = new System.Windows.Thickness(Location[0], Location[1], 0, 0);
EditButton.Height = double.Parse("20");
EditButton.Width = double.Parse("20");
EditButton.Cursor = System.Windows.Input.Cursors.Hand;
EditButton.Content = "TEST!";
EditButton.Click += new System.Windows.RoutedEventHandler(Edit_Click);
Grid.Children.Add(EditButton);
Location[1] += 17;

当我没有定义 EditButton.Margin 时,该按钮可以正常工作,但是一旦我定义它,我就无法单击它并且光标不会改变。我已经在互联网上搜索了答案,但似乎没有一个有效。提前致谢。

【问题讨论】:

  • 这里的位置是什么?
  • 什么是网格?如果那个 Grid,你应该设置附加属性吗?作为旁注,EditButton.Height = 20; 有什么问题?

标签: c# wpf


【解决方案1】:

如果不能点击自己创建的控件,一般是其他控件在上面造成的。

我建议稍微修改一下你的代码,然后继续前进:

var stackPanel = new StackPanel();
var button = new Button();
button.Content = "Your Button";
button.Click += new System.Windows.RoutedEventHandler(Edit_Click);
stackpanel.Children.Add(button);

我建议使用StackPanel,因为它会自动排列您的控件,从而防止它重叠,您可以从这一点开始查看问题是由网格还是其他组件引起的。

Button 默认会拉伸到其内容,StackPanel 也会如此。

【讨论】:

    【解决方案2】:

    不确定代码中的“位置”是什么,我假设“网格”是网格的名称。下面的作品。

    public MainWindow()
        {
            InitializeComponent();
            Button EditButton = new Button();
            EditButton.Margin = new System.Windows.Thickness(10, 10, 0, 0);
            EditButton.Height = double.Parse("20");
            EditButton.Width = double.Parse("20");
            EditButton.Cursor = System.Windows.Input.Cursors.Hand;
            EditButton.Content = "TEST!";
            EditButton.Click += new System.Windows.RoutedEventHandler(Edit_Click);
            Grid.Children.Add(EditButton);
          //  Location[1] += 17;
        }
    
    private void Edit_Click(object sender, RoutedEventArgs e)
    {
        throw new NotImplementedException();
    }
    

    XAML -

    <Window x:Class="WpfApplication6.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 x:Name="Grid">
    
        </Grid>
    </Window>
    

    【讨论】:

      【解决方案3】:

      看起来您想以编程方式执行此操作,但如果您在 XAML 中定义它,您可以将按钮的 Panel.ZIndex 属性设置为某个较高的数字以将其置于最前面:

      <Button Content="TEST!" Panel.ZIndex="1000" Height="20" Width="20" Cursor="Hand" Click="Edit_Click" />
      

      希望对某人有所帮助...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 2014-05-03
        • 1970-01-01
        • 2023-04-07
        • 2016-08-14
        • 2020-01-22
        相关资源
        最近更新 更多