Search code examples
c#wpfdata-bindingbindingbinding-expressions

Need help resolving a BindingExpression issue


I have this style:

                <DataTemplate>
                    <Button
                        Width="44"
                        Height="24"
                        VerticalAlignment="Top"
                        VerticalContentAlignment="Center"
                        HorizontalAlignment="Left"
                        HorizontalContentAlignment="Center"
                        Command="{Binding UninspectedPrintSelectedCommand}"
                        CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}">

But the command does not work correctly. Looking at the output window yields this issue:

System.Windows.Data Error: 40 : BindingExpression path error: 'UninspectedPrintSelectedCommand' property not found on 'object' ''String' (HashCode=701007577)'. BindingExpression:Path=UninspectedPrintSelectedCommand; DataItem='String' (HashCode=701007577); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')

ViewModel ICommand Property:

    public ICommand UninspectedPrintSelectedCommand
    {
        get
        {
            return new DelegateCommand<object>((print) =>
            {
                string printName = print.ToString();
                int indexOfX = printName.IndexOf('x');
                Row = DiePrint.GetRow(printName);
                Col = DiePrint.GetCol(printName);

                if (diePrint == null) { diePrint = new DiePrint(Row + "x" + Col); }
                else
                {
                    diePrint.Row = Convert.ToInt32(row);
                    diePrint.Col = Convert.ToInt32(col);
                }
                LoadMap();
            });
        }
    }

I have no idea how to resolve this. How is the Command property of the Button being interpreted as a String?

If it means anything, this is in my App.xaml file, not the main window.


Solution

  • I think what you want is to have your binding use a source higher up in your visual tree, where the DataContext is set to the viewmodel you want, rather than being set to a string.

    For example, assuming there is a Grid higher up with the right data context, you would use a binding like this:

    {Binding DataContext.UninspectedPrintSelectedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}
    

    Replace Grid with something that will reliably be in the visual tree at the right level.