【问题标题】:C#/AvaloniaUI - Click a button and change TextC#/AvaloniaUI - 单击按钮并更改文本
【发布时间】:2020-01-26 18:53:58
【问题描述】:

我对 AvaloniaUI 很陌生。

单击按钮时,我真的很难更改文本。 这是我的代码:

  <Window xmlns="https://github.com/avaloniaui"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
          mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
          x:Class="ReadyForWar_Launcher.MainWindow"
          Title="ReadyForWar_Launcher">
    <StackPanel>
      <TextBlock Name="TestBlock">Show my text here!</TextBlock>
      <Button Command="{Binding RunTheThing}" CommandParameter="Hello World">Change the Text!</Button>
    </StackPanel>
  </Window>

这是我的 MainWindow.xaml.cs:

using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace ReadyForWar_Launcher
{
    public class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
#if DEBUG
            this.AttachDevTools();
#endif
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }

        public void RunTheThing()
        {

        }
    }
}

RunTheThing 里面我不知道如何选择 Name="TestBlock" 的 TextBlock 并将文本更改为“Hello World”。

你能帮我解决这个问题吗?

【问题讨论】:

    标签: c# avaloniaui


    【解决方案1】:

    有两种方法,一种是推荐的,一种是直接的。

    推荐:使用 MVVM 模式。使用ButtonTextPropertyRunTheThing 命令创建视图模型,使用命令更改属性,将该模型分配给DataContext,然后绑定按钮文本和命令以查看模型属性。 MVVM 方法与 WPF 中的方法基本相同,因此您可以从那里使用文档和教程(这适用于大多数 Avalonia,顺便说一句)。例如,这里是good one(不是广告,来自 google 的第 4 个链接)。

    直截了当(又名 winforms-way):将 x:Name="MyButton" 添加到您的按钮并在调用 AvaloniaXamlLoader.Load(this); 后使用 this.FindControl&lt;Button&gt;("MyButton")。这将为您提供一个Button 引用,您可以从代码中对其进行操作。您可以直接从代码隐藏订阅点击处理程序,而不是使用命令,将public void MyButton_OnClick(object sender, RoutedEventArgs args){} 添加到您的MainWindow 类并添加替换命令和命令参数为Click="MyButton_OnClick"。这样按钮单击将触发您的事件处理程序。

    请注意,第二种方法不能很好地适应应用程序的大小,并且在处理列表时会受到代码复杂性的影响。

    【讨论】:

    • 您好,感谢您的回答。但是,Avalonia 似乎不允许使用Click="MyButton_OnClick" Click 我认为不再允许使用。能否请您对第一种方法做出更详细的回答?
    • Button 类中的点击事件does exist。确保事件处理程序签名匹配并且处理程序是公开的。
    • 我会试试的!谢谢你。你能用Click=""方法试试一个例子吗?我在尝试使用该方法时收到错误消息?
    • &lt;Button Click="MyButton_Click"&gt;Test&lt;/Button&gt;public void MyButton_Click(object sender, RoutedEventArgs args) =&gt; ((Button) sender).Content = "New text"; in MainWindow.xaml.cs 为我工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多