Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing the instance of a custom control within a static method

In WPF I have created a custom control for a button.
I would like this button to become ‘enabled’ when a target datagrid has some cells selected, otherwise it should become ‘disabled’.

This is my code:

public class MyCustomButton: Button
{

    public DataGrid TargetDataGrid
    {
        get { return (DataGrid)GetValue(TargetDataGridProperty); }
        set { SetValue(TargetDataGridProperty, value); }
    }
    public static readonly DependencyProperty TargetDataGridProperty =
        DependencyProperty.Register("TargetDataGrid", typeof(DataGrid), typeof(MyCustomButton), new PropertyMetadata(new PropertyChangedCallback(OnTargetDatagridChanged))); 

    private static void OnTargetDatagridChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (e.OldValue is DataGrid oldGrid)
        {
            oldGrid.SelectedCellsChanged -= DataGrid_SelectedCellsChanged;
        }
        if (e.NewValue is DataGrid currDg)
        {
            currDg.SelectedCellsChanged += DataGrid_SelectedCellsChanged;
        }
    }

    private static void DataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        if (sender is DataGrid dg && dg.SelectedCells.Any())
        {
           // how can I disable/enable this button since we are in a static method? 
           // IsEnabled = true
        } 
        else 
        {
           // IsEnabled = false
        }
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Do not declare the event handler as a static method:

private static void OnTargetDatagridChanged(
    DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var button = (MyCustomButton)d;

    if (e.OldValue is DataGrid oldDg)
    {
        oldDg.SelectedCellsChanged -= button.DataGrid_SelectedCellsChanged;
    }
    if (e.NewValue is DataGrid newDg)
    {
        newDg.SelectedCellsChanged += button.DataGrid_SelectedCellsChanged;
    }
}

private void DataGrid_SelectedCellsChanged(
    object sender, SelectedCellsChangedEventArgs e)
{
    IsEnabled = sender is DataGrid dg && dg.SelectedCells.Any();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading