猿问

如何设置 WPF 按钮的文本

我不知道如何在按钮上显示文本。


现在这是我问题的根源。我有这三个按钮,我想显示一个小文本:“开始”、“停止”和“重置”。


using System.Windows.Controls;



namespace Program.src.View.Main

{

    public class LowerActionPanel : StackPanel

    {

        public LowerActionPanel()

        {

            this.Orientation = Orientation.Horizontal;

            this.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;


            Button startButton = new Button();

            startButton.Width = 90;

            startButton.Height = 25;

            startButton.Text = "Text"; //(here the problem lies)

            this.Children.Add(startButton);


            Button stopButton = new Button();

            stopButton.Width = 90;

            stopButton.Height = 25;

            this.Children.Add(stopButton);


            Button resetButton = new Button();

            resetButton.Width = 90;

            resetButton.Height = 25;

            this.Children.Add(resetButton);

        }

    }

}

另一个问题中,他们使用 .Text 没有任何问题,这让我认为可以只使用它,或者我只是弄错了?



陪伴而非守候
浏览 322回答 2
2回答

侃侃尔雅

您正在使用 WPF。您提供的最后一个示例链接使用 WinForms。WinForms 在按钮上提供属性 Text 而 WPF 按钮没有。如果要设置 WPF 按钮的内容,应使用 Content 属性。像这样:var button = new Button();button.Content = "Click here";或者使用对象初始值设定项:var button = new Button {Content = "Click here"};

慕妹3146593

我认为您正在做的可能应该是用户控件而不是自定义控件。也许是这样的:<UserControl x:Class="wpf_99.UserControl1"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;xmlns:d="http://schemas.microsoft.com/expression/blend/2008"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;xmlns:local="clr-namespace:wpf_99"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;mc:Ignorable="d"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Height="25"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;><UserControl.Resources>&nbsp; &nbsp; <Style TargetType="Button">&nbsp; &nbsp; &nbsp; &nbsp; <Setter Property="Width" Value="92"/>&nbsp; &nbsp; &nbsp; &nbsp; <Setter Property="Margin" Value="2"/>&nbsp; &nbsp; </Style></UserControl.Resources><StackPanel Orientation="Horizontal">&nbsp; &nbsp; <Button Name="StartButton" Content="Start"/>&nbsp; &nbsp; <Button Name="StopButton" Content="Stop"/>&nbsp; &nbsp; <Button Name="ResetButton" Content="Reset"/></StackPanel></UserControl>用法:&nbsp;<Window&nbsp; &nbsp; ...&nbsp; &nbsp; xmlns:local="clr-namespace:wpf_99"&nbsp; &nbsp; ><Grid>&nbsp; &nbsp; <local:UserControl1 HorizontalAlignment="Left" VerticalAlignment="Top"/></Grid>您可能会发现这很有用:https://social.technet.microsoft.com/wiki/contents/articles/32610.wpf-layout-lab.aspx
随时随地看视频慕课网APP
我要回答