Question

I am trying to execute a bound command from my code behind utilizing the UiElement. button.Command.Execute(button.CommandParameter)

However, at this point the Command property of the button is null. simultaneously when I check the command in my View Model the property is set. The only diagnosis I can come up with is that until the window is actually visible the command is not bound to the command property of the button. I feel like may I'm missing a step somewhere or my implementation is not sound. below is some snipits of the code, please let me know if you need more.

Window constructor:

public PlottingViewModel ViewModel { get; set; }

public PlottingGUI()
{
    InitializeComponent();
    DataContext = (ViewModel = new PlottingViewModel());
    _setDefaultSelections();
}

IList<RadioButton> buttons;

Setting default selections:

private void _setDefaultSelections()
{
    buttons = new List<RadioButton>();
    _getRadioButtons(this);
    foreach (var setting in ViewModel.Settings.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
    {
        var settingValue = setting.GetValue(ViewModel.Settings);
        var button = buttons.FirstOrDefault(btn => btn.Content.Equals(settingValue)
                || ((string)btn.CommandParameter).Equals(settingValue));

        if (button == null)
            continue;
        button.IsChecked = true;

        // NullReference here
       // button.Command.Execute(button.CommandParameter);
    }
}

one of the RadioButtons XAML:

<RadioButton Content="None"
             Grid.Row="0"
             Command="{Binding StampedCommand}"
             CommandParameter="None"
             Foreground="WhiteSmoke"/>

I feel, the only way i may be able to successfully complete this task is to execute the command directly from my viewmodel. (Which i don't want to do)

Thanks for reading..

Was it helpful?

Solution

To sum up comments at the point when you're calling _setDefaultSelections() bindings have not been updated yet, hence Command is still null, so you have to wait until everything is loaded. You can call _setDefaultSelections during Loaded event

Occurs when the element is laid out, rendered, and ready for interaction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top