Question

I'm new to WPF and am trying to create an interface that builds itself from a XML file. The newly built interface contains different controls like textboxes, labels or buttons. And the last one gave me a headache for days, because every button shall get its own command.

Example XML Code for buttons:

ID="1001" GroupID="1" Control="Button" Content="Apply" Margin="2" Width="60"

And this is the method that defines each button:

public Button Button(XElement xElement, Button newButton)
{
    if (xElement.Attribute("Width") != null)
        newButton.Width = Convert.ToDouble((xElement.Attribute("Width").Value));
        
    if (xElement.Attribute("Content") != null)
    {
        string sContent = xElement.Attribute("Content").Value;

        //Here gets the button its command
        Commands Commands = new Commands();
        Commands.setCommand(sContent, newButton);
        newButton.Content = sContent;
    }
    return newButton;
}

The Content Attribute names the button and the function at the same time.

Problem: Basically I am trying to build a commands class that contains all possible commands. Each time a button is created the setCommand(sContent, newButton) method scans the commands class and sets up the matching command to this button via a Switch-Case statement.

And now each time the button is clicked the assigned command should fire. But is it even possible to do it this way, or am I on the wrong track? Is there an easier solution to do this or am I just missing essentials of command binding?

Any hint is appreciated.

Was it helpful?

Solution

First of all, if you have your own commands defined that you want to bind to Buttons on your UI, then they should be exposed via public properties in your VM or DataContext of your UI.

Then once you have this arrangement in place, you can set the Command on button like below:

Binding binding = new Binding();
binding.Path = new PropertyPath("MyCommand"); //Name of the property in Datacontext
button.SetBinding(Button.CommandProperty, binding);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top