为了账号安全,请及时绑定邮箱和手机立即绑定

如何设置 WPF 按钮的文本

如何设置 WPF 按钮的文本

C#
陪伴而非守候 2022-12-31 10:31:46
我不知道如何在按钮上显示文本。现在这是我问题的根源。我有这三个按钮,我想显示一个小文本:“开始”、“停止”和“重置”。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 没有任何问题,这让我认为可以只使用它,或者我只是弄错了?
查看完整描述

2 回答

?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

您正在使用 WPF。您提供的最后一个示例链接使用 WinForms。WinForms 在按钮上提供属性 Text 而 WPF 按钮没有。如果要设置 WPF 按钮的内容,应使用 Content 属性。


像这样:


var button = new Button();

button.Content = "Click here";

或者使用对象初始值设定项:


var button = new Button {Content = "Click here"};


查看完整回答
反对 回复 2022-12-31
?
慕妹3146593

TA贡献1820条经验 获得超9个赞

我认为您正在做的可能应该是用户控件而不是自定义控件。


也许是这样的:


<UserControl x:Class="wpf_99.UserControl1"

         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 

         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 

         xmlns:local="clr-namespace:wpf_99"

         mc:Ignorable="d" 

         Height="25"

         >

<UserControl.Resources>

    <Style TargetType="Button">

        <Setter Property="Width" Value="92"/>

        <Setter Property="Margin" Value="2"/>

    </Style>

</UserControl.Resources>

<StackPanel Orientation="Horizontal">

    <Button Name="StartButton" Content="Start"/>

    <Button Name="StopButton" Content="Stop"/>

    <Button Name="ResetButton" Content="Reset"/>

</StackPanel>

</UserControl>

用法:


 <Window

    ...

    xmlns:local="clr-namespace:wpf_99"

    >


<Grid>

    <local:UserControl1 HorizontalAlignment="Left" VerticalAlignment="Top"/>

</Grid>

您可能会发现这很有用:


https://social.technet.microsoft.com/wiki/contents/articles/32610.wpf-layout-lab.aspx


查看完整回答
反对 回复 2022-12-31
  • 2 回答
  • 0 关注
  • 321 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号