How to exit a method and return control back to the user, and not to the calling method?

I have a list and a button next to it that uses the selected item to perform an action. If the user does not make a choice, but presses a button, they are invited to make a choice first.

What I have below works, but is there a way where the calling method should not have an if (not selected) return statement? I want to just call the selectionFound () method from other events that are list dependent? I would like the selectionFound method to lose its temper not only by itself, but also the calling method and return control back to the user. So instead of returning true / false, as shown below, I would just like to return another keyword as well.

private void deleteData()
{
 // if nothing selected, warn user and return control
 if(!selectionFound()) return;
        .....
}

private bool selectionFound()
{
 // make sure user selected an item from listview, warn and exit if not
 if (lvwInventory.SelectedIndex == -1)
 {
  MessageBox.Show("Please select an item first");
  return false;
 }
 else
  return true;
}
+3
6

, , , , , , , .

EDIT: , , - .

+3

? xaml , .

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <ListView x:Name="listy">
        <ListViewItem>one
        </ListViewItem>
        <ListViewItem>two
        </ListViewItem>
        <ListViewItem>three
        </ListViewItem>
    </ListView>
    <Button Grid.Row="1" Content="Clicky">
        <Button.Style>
            <Style TargetType="Button">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding SelectedItem, ElementName=listy}" Value="{x:Null}">
                        <Setter Property="IsEnabled" Value="False"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</Grid>
+2

selectionFound() deleteData ; , , .

; . - , ; ( , , )

0

, , , ... , , - deleteData selectionFound . .

0

, "" selectionfound(). , :

private void deleteData()
{
 // if nothing selected, warn user and return control
 if(lvwInventory.SelectedIndex == -1)
 {
  MessageBox.Show("Please select an item first");
  return;
 }
 // Rest of function below...
}

SelectedIndex ( ) , selectionfound(). deleteData() return , .

, , , 5 - . , .

0

You can use the listView event to include other controls. If your button is disabled by default, enable it when an event with a listView change indicates that the user has selected something. Personally, I still check the value, but you can be pretty sure that it exists if you did this on a button click event.

And in case it's not obvious what I'm getting, you can exclude the foundSelection () check from the click handler.

0
source

Source: https://habr.com/ru/post/1774181/


All Articles