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, but I only know how that works in the XAML
like this:
<Custom:SurfaceButton Command="{Binding SaveReservationCommandBinding, Mode=OneWay}"/>
But I cannot do it like this because my buttons do not exist in the XAML, only in the code behind.
So how would a command binding like that works in code behind?
Assuming that you have a named your SurfaceButton to "SurfaceButton1" and you have access to an instance of the command, you can use the following code:
I took the code from the link posted by Anvaka as template. I use RadMenuItem of Telerik, but surely you can use any other component that expose Command property.
Hope it helps ... and if something is not clear, sorry, it's my first post :)
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: