Steven Coco Steven Coco - 2 months ago 15
C# Question

How to bind element Content to custom Command property

I have a custom ICommand class, to which I am trying to add properties "DisplayName" and "ToolTipText":

internal class MyCommand : ICommand
{
// ...
internal string DisplayName {
get { return displayName; }
set {
if (displayName == value)
return;
if (value == null)
value = "";
displayName = value;
OnPropertyChanged(nameof(DisplayName));
}
}

internal string ToolTipText {
get { return toolTipText; }
set {
if (toolTipText == value)
return;
if (value == null)
value = "";
toolTipText = value;
OnPropertyChanged(nameof(ToolTipText));
}
}
// ...
}


in XAML, I bind the command to a Button, and I want to set the button Content from the DisplayName on the Command. The following produces a result:

Content="{Binding Command, RelativeSource={RelativeSource Self}}"


The button's Content is ToString() on the Command. But I can't access properties on the custom ICommand object.

My ViewModel returns the custom type for the ICommand:

public MyCommand MyButtonCommand {
get {
return myButtonCommand?? (myButtonCommand = new MyCommand (
// ...
);
}
}


But XAML syntax like these do not work:

Content="{Binding Command.DisplayName, RelativeSource={RelativeSource Self}}"

Content="{Binding Command/DisplayName, RelativeSource={RelativeSource Self}}"


Any answers?

Answer

The following xaml are both working

the classical, standard one

Content="{Binding MyButtonCommand.DisplayName}" Command="{Binding MyButtonCommand}"

the quite unusual

`Content="{Binding Command.DisplayName, RelativeSource={RelativeSource Self}}" Command="{Binding MyButtonCommand}`"

assuming that both MyCommand and DisplayName are public and not internal

  public class MyCommand : ICommand
    {
        public string DisplayName

and that DisplayName has a value...

Comments