Search code examples
c#wpfmvvmcommandparameter

How to pass ContentControl Element to CommandParameter?


I have a toolbar that show many Button with Image and TextBlock.

Then, I create a CommandManager to manager all Button's commands. So, I want to implement a factory to assign action by Button's TextBlock.

This is my xaml and Command function, I try to pass all Button's Text, but I don't know how to do.

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Command" Value="{Binding ActionCommand}"/>
            <Setter Property="CommandParameter" Value="{Binding Path=Text}"/>
        </Style>
    </StackPanel.Resources>
    <Button>
        <StackPanel>
            <Image Source="/Resources/ToolBar/open.png"/>
            <TextBlock Text="Open"/>
        </StackPanel>
    </Button>
    <Button>
        <StackPanel>
            <Image Source="/Resources/ToolBar/save.png"/>
            <TextBlock Text="Save"/>
        </StackPanel>
    </Button>
</StackPanel>

ActionManager:

public ICommand ActionCommand { get { return new RelayCommand(_onActionCommand); } }

private void _onActionCommand(object parameter)
{
    if (parameter == null)
    {
        return;
    }

    string buttonContent = parameter as string;
    switch (buttonContent)
    {
        case "Open":
            new OpenWindow().ShowDialog();
            break;
        case "Open":
            new Save();
            break;
    }
}

Solution

  • A Button has no concept of "Text" but you could set the Tag property to a string and pass this one:

    <StackPanel>
        <StackPanel.Resources>
            <Style TargetType="{x:Type Button}">
                <Setter Property="Command" Value="{Binding ActionCommand}"/>
                <Setter Property="CommandParameter" Value="{Binding Path=Tag, RelativeSource={RelativeSource Self}}"/>
            </Style>
        </StackPanel.Resources>
        <Button Tag="Open">
            <StackPanel>
                <Image Source="/Resources/ToolBar/open.png"/>
                <TextBlock Text="Open"/>
            </StackPanel>
        </Button>
        <Button Tag="Save">
            <StackPanel>
                <Image Source="/Resources/ToolBar/save.png"/>
                <TextBlock Text="Save"/>
            </StackPanel>
        </Button>
    </StackPanel>