You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fody未触发Button状态重评估,Start按钮无法自动启用求助

问题原因及解决方案

核心问题分析

  1. 按钮绑定冲突:Start按钮同时绑定了Command和IsEnabled。WPF中ICommand接口的CanExecute方法会自动控制按钮的IsEnabled状态,手动绑定IsEnabled会覆盖这个自动逻辑,且你的CanPress属性从未被更新(默认值为false),导致按钮一直不可用。
  2. Command未触发状态更新:当FilePath或SelectedItem变化时,StartCommand的CanExecute状态不会自动重新评估,需要手动触发变更通知。

步骤1:修复XAML按钮绑定

移除Start按钮的IsEnabled绑定,让Command自动管理按钮可用性:

<Button
    Grid.Row="4"
    Grid.ColumnSpan="2"
    Margin="10,0,10,10"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Bottom"
    Content="Start"
    Command="{Binding StartCommand}" />

步骤2:更新ViewModel,触发Command状态变更

在ViewModel中订阅PropertyChanged事件,当FilePath或SelectedItem变化时,调用StartCommand.ChangeCanExecute()重新评估CanStartAction:

[AddINotifyPropertyChangedInterface]
public class AudioPageViewModel : INotifyPropertyChanged
{
    public string? FilePath { get; set; }
    public bool IsWorking { get; set; }
    public string? SelectedItem { get; set; }
    public List<string>? Languages { get; set; }
    public Visibility CanShow { get; set; }
    public DialogHelper Dialog { get; }
    public Command PickFileCommad { get; set; }
    public Command StartCommand { get; set; }

    public AudioPageViewModel()
    {
        InitListLanguages();
        Dialog = new DialogHelper();
        CanShow = Visibility.Hidden;
        PickFileCommad = new Command(PickFileAction);
        StartCommand = new Command(StartAction, CanStartAction);
        
        PropertyChanged += AudioPageViewModel_PropertyChanged;
    }

    private void AudioPageViewModel_PropertyChanged(object? sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(FilePath) || e.PropertyName == nameof(SelectedItem))
        {
            StartCommand.ChangeCanExecute();
        }
    }

    private bool CanStartAction(object arg)
    {
        return !string.IsNullOrEmpty(SelectedItem) && !string.IsNullOrEmpty(FilePath);
    }

    private void StartAction(object obj)
    {
        throw new NotImplementedException();
    }

    private void PickFileAction()
    {
        var filePath = Dialog.GetFilePath(ConstantsHelpers.AUDIO);
        FilePath = filePath;
    }

    private void InitListLanguages()
    {
        Languages = new List<string>() {
            "English",
            "Spanish"
        };
    }

    public event PropertyChangedEventHandler? PropertyChanged;
}

步骤3:清理无用代码

删除未使用的CanPress属性:

// 移除该行代码
// public bool CanPress { get; set; }

额外说明

  • Fody的AddINotifyPropertyChangedInterface会自动为属性生成PropertyChanged事件通知,通过订阅该事件可以监听关键属性的变化。
  • ChangeCanExecute()方法会触发CanExecuteChanged事件,通知按钮重新调用CanStartAction,从而更新按钮的可用状态。

内容的提问来源于stack exchange,提问作者edu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:50:35