4

我有一个简单的 Avalonia 表格:

<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="AvaloniaExperiment.MainWindow"
        Title="AvaloniaExperiment">
  <StackPanel>
    <TextBlock>Welcome to Avalonia!</TextBlock>
    <Button Name="btn" Click="btn_OnClick">Fred!</Button>
  </StackPanel>
</Window>

以及后面代码中的一个方法(我想以这种方式做事,直到我熟悉 Avalonia,然后也许我会尝试 MVVM):

private void btn_OnClick()
{
    btn.Text = "Ginger";
}

但是我得到这些编译错误:

名称 btn 在当前上下文中不存在(在后面的代码中)

无法为参数 System.Private.CoreLib:System.String 的 Avalonia.Controls:Avalonia.Controls.Button 类型的属性 Click 找到合适的设置器或加法器,可用的设置器参数列表为:System.EventHandler`1[[Avalonia.Interactivity。 RoutedEventArgs,Avalonia.Interactivity,版本=0.9.0.0,文化=中性,PublicKeyToken=null]](在 XAML 中)

无法为参数 System.Runtime:System.String 类型的 Avalonia.Controls:Avalonia.Controls.Button 属性命令找到合适的设置器或加法器,可用的设置器参数列表为:Avalonia.UnsetValueType Avalonia.Data.IBinding System.Windows.Input .ICommand(也在 XAML 中)

在连接这个事件处理程序时我做错了什么?

4

4 回答 4

1

你有没有尝试过...

public void btn_OnClick(object sender, RoutedEventArgs e)
{
    btn.Text = "Ginger";
}
于 2020-05-17T01:42:16.943 回答
1

您应该像这样在父控件构造函数中添加一个 ControlLink:

public class AnyParentControl
{
    Button btn; // for the class
    public AnyParentControl() // constructor
    {
        InitializeComponent(); // necessary method for Avalonia

        btn = this.Find<Button>("The Control Name on XAML File");
        btn.Click += Cbtn_Click; // event link
    }
}

来自秘鲁的问候:D

于 2020-06-18T02:50:58.213 回答
0

sender您刚刚单击的按钮,因此将 sender 类型转换为 Button 并将其 Content 属性(而不是 Text)设置为您想要的任何内容。

public void btn_OnClick( object? sender, RoutedEventArgs args )
{
    ( sender as Button )!.Content = "Ginger";
}

无需在树或其他任何东西中查找它,这样您就可以为所有按钮重用相同的代码,例如,根据它是哪个按钮,设置不同的名称或样式或其他属性等。

更先进:

public void btn_OnClick( object? sender, RoutedEventArgs args )
{
    var button = ( sender as Button )!;
    switch ( button.Name )
    {
        case "btn":
        {
            button.Content = "Ginger";
        }
        break;
        case "otherBtn":
        {
            button.Content = "Ale";
        }
        break;
        default:
        {
            button.Content = "No clue which Button you are!";
        }
        break;
    }
}
于 2021-11-09T00:28:47.267 回答
0

按钮没有Text属性。它确实有Content

btn.Content = "Ginger";
于 2020-05-17T00:13:25.650 回答