【问题标题】:C#/WPF/Avalonia - On button click change textC#/WPF/Avalonia - 在按钮上单击更改文本
【发布时间】:2020-01-27 18:43:55
【问题描述】:

我正在使用 Avalonia 0.9.2。

我对它很陌生,按下按钮时我无法更改文本。

这是我的MainWindow.xaml

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:ReadyForWar_Launcher.ViewModels;assembly=ReadyForWar_Launcher"
        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.Views.MainWindow"
        Icon="/Assets/avalonia-logo.ico"
        Title="ReadyForWar_Launcher">

    <Design.DataContext>
        <vm:MainWindowViewModel/>
    </Design.DataContext>

  <StackPanel>
    <Button Content="Update the Text" Command="{Binding UpdateText}" CommandParameter="Hello World!"></Button>
    <TextBlock Text="{Binding Message}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
  </StackPanel>


</Window>

这是我的MainWindowViewModel

public class MainWindowViewModel : ViewModelBase
{
    public string Message = "Welcome to Avalonia!";
    public void UpdateText(object text)
    {
        Message = (string)text;
    }
}

当我点击按钮Update the Text 时没有任何反应?这是为什么?我想将Message 的文本更新为Hello world!,但没有任何反应。

为什么会这样,我的错误在哪里?

【问题讨论】:

  • 点击按钮时是否会触发UpdateText 方法?
  • 我不知道如何测试。
  • 只要在方法入口处放断点
  • 看起来是进去了,但没有改变文字...
  • 我没有使用 Avalonia,但我猜 Text 必须是一个属性,可能带有一些更改通知

标签: c# wpf avaloniaui


【解决方案1】:

看看这个page

using ReactiveUI;

public class MyViewModel : ReactiveObject
{
    private string caption;

    public string Caption
    {
        get => caption;
        set => this.RaiseAndSetIfChanged(ref caption, value);
    }
}

这意味着要在 UI 中反映更改,该属性需要实现INotifyPropertyChanged 接口。仔细阅读。

【讨论】:

  • 您好,请您给出一个完整的答案,并举例说明它应该如何工作?
猜你喜欢
  • 2020-11-17
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
相关资源
最近更新 更多