programing

WPF 버튼을 ViewModelBase 명령어에 바인드하려면 어떻게 해야 합니까?

mailnote 2023. 4. 21. 21:10
반응형

WPF 버튼을 ViewModelBase 명령어에 바인드하려면 어떻게 해야 합니까?

나는 전망이 있다.AttributeView모든 종류의 속성이 포함되어 있습니다.또한 버튼을 누르면 기본값이 속성으로 설정됩니다.저도 있어요.ViewModelBase가지고 있는 모든 ViewModel의 기본 클래스인 클래스입니다.문제는 WPF에서 명령어에 바인딩된 버튼을 얻을 수 없다는 것입니다.

시도해 봤지만 아무 소용이 없어요

<Button Command="{Binding DataInitialization}" Content="{x:Static localProperties:Resources.BtnReinitializeData}"></Button>

명령어는 (에서) 정의되어 있습니다.ViewModelBase)는 다음과 같습니다.

public CommandBase DataInitialization { get; protected set; }

응용 프로그램 부팅 시 다음 명령어에 대한 새 인스턴스가 생성됩니다.

DataInitialization = new DataInitializationCommand()

다만, WPF 바인딩은 커맨드를 「검색」하지 않는 것 같습니다(버튼을 눌러도 아무것도 하지 않습니다).현재 뷰에서 사용되는 ViewModel은ViewModelBase그 밖에 어떤 것을 시도해 볼 수 있을까요(WPF에 익숙하지 않기 때문에 매우 간단한 질문일 수 있습니다.

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

창 뒤에 있는 코드:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

View Model:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

명령 핸들러:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

이게 당신에게 아이디어를 주길 바랍니다.

언급URL : https://stackoverflow.com/questions/12422945/how-to-bind-wpf-button-to-a-command-in-viewmodelbase

반응형