WPF: Binding to commands in code behind

后端 未结 4 1161
梦如初夏
梦如初夏 2021-01-01 23:23

I have a WPF Microsoft Surface Application and I\'m using MVVM-Pattern.

I have some buttons that are created in code behind and I would like to bind commands to them

4条回答
  •  鱼传尺愫
    2021-01-01 23:55

    The accepted answer will work great if the Button has access to the Command. However, in MVVM these are usually kept separate (the Button in the View and the Command in the View-Model). In XAML you'd normally use a data binding to hook it up (like the example in the question).

    My program gave me an error when my dynamic Button couldn't find the Command (because it was in a totally different namespace). This is how I ended up solving this:

    SurfaceButton.SetBinding (Button.CommandProperty, new Binding("SaveReservationCommand"));
    

提交回复
热议问题