Search code examples
wpfbuttondatagridwpf-controlsmvvm-light

WPF MVVM Light enabling button if data grid row is selected


I can't seem to find a straight answer on this anywhere. I have a button that I want to Disable UNTIL a DataGrid row is selected. Doesn't matter which row. Once it's deselected I would like it to be disabled again.


Solution

  • here you go

    <StackPanel>
        <DataGrid x:Name="dGrid">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding}"
                                    Header="A Column" />
            </DataGrid.Columns>
            <sys:String>item 1</sys:String>
            <sys:String>item 2</sys:String>
            <sys:String>item 3</sys:String>
            <sys:String>item 4</sys:String>
        </DataGrid>
        <Button x:Name="button"
                Content="A Button">
            <Button.Style>
                <Style TargetType="Button">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding SelectedItems.Count,ElementName=dGrid}"
                                     Value="0">
                            <Setter Property="IsEnabled"
                                    Value="False" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
    </StackPanel>
    

    above example will place a trigger on SelectedItems.Count of DataGrid and will disable the button if it is zero

    this is a pure xaml solution, other solution may also be possible with converters or vm properties


    EDIT

    as requested here is a sample to do it without using Name attribute

    <StackPanel>
        <DataGrid>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding}"
                                    Header="A Column" />
            </DataGrid.Columns>
            <sys:String>item 1</sys:String>
            <sys:String>item 2</sys:String>
        </DataGrid>
        <Button Content="A Button">
            <Button.Style>
                <Style TargetType="Button">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Parent.Children[0].SelectedItems.Count,RelativeSource={RelativeSource Self}}"
                                     Value="0">
                            <Setter Property="IsEnabled"
                                    Value="False" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
            </Button>
    </StackPanel>
    

    above code assume the datagrid to be the first child of the parent container Parent.Children[0], you may adjust it as per your needs.