C#:如何更改 MVVM 中的按钮图标?

标签 c# wpf button mvvm

我尝试通过 Click_Event 更改 Button 图标,所以目前我有这样的 xaml:

<Button Content="{materialDesign:PackIcon LanDisconnect}" Command="{Binding Connect}" />

在 ViewModel 中:

public ICommand Connect
{
    get
    {
        _Connect = new RelayCommand(
            param => ConnectChip());
        return _Connect;
    }
}

如何在 Connect 命令中将 Button 图标更改为 {MaterialDesign:PackIcon LanConnect}?谢谢!

最佳答案

虽然一些评论建议稍微更高级的解决方案(例如使用 DataTriggers)。我建议(至少开始时)您只需要为按钮内容添加绑定(bind)。然后,您可以将属性添加到 View 模型并通过命令更新它。

在您的情况下,您使用的是 Material Design内容。

因此在您的 View 模型中,您需要包含一个图标属性:

using MaterialDesignThemes.Wpf;

public PackIconKind IconKind
{
    get { return _IconKind; }
    set { SetField(ref _IconKind, value); }
}
private PackIconKind _IconKind = PackIconKind.LanDisconnect;

See this reference for the SetField method

然后将您的按钮 XAML 更改为:

<Button Command="{Binding MyCommand}" Width="100" Height="32">
    <materialDesign:PackIcon Kind="{Binding IconKind}" />
</Button>

这为按钮中的图标设置了绑定(bind)。现在, View 模型可以随时更改此 Kind。我更喜欢在构造函数中设置命令。我首先有一个命令属性如下:

public ICommand MyCommand { get; }

在构造函数中:

MyCommand = new RelayCommand(UpdateIcon);

然后将 UpdateIcon 方法添加到 View 模型中。然后可以从其他地方调用此方法(不仅仅是按钮命令)。

protected void UpdateIcon()
{
    IconKind = MaterialDesignThemes.Wpf.PackIconKind.LanConnect;
}

关于C#:如何更改 MVVM 中的按钮图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45558011/

相关文章:

c# - 如何编写组合字符的正则表达式?

c# - 在wpf中导出RadRichTextBox内容

c# - 使用 ToDictionary 创建字典

swift - 我该如何修复错误 "Thread 1: signal SIGABRT"?

html - 如何动态更改破折号中的 html.Button 文本?

c# - 在 C# 中对值进行零填充的简单而优雅的方法

c# - 使用 Infragistics 对话框窗口平铺窗口偏移

c# - 使用 ReactiveUI 与 PasswordBox 进行两种方式绑定(bind)

c# - 仅在选择选项卡时运行查询 WPF MVVM

jquery - 获取对启动 jQuery 对话框的按钮的引用