speccaN
speccaN

Reputation: 77

TreeView on Focus Leave - disable button

I am trying to have a Button which

  1. gets Enabled when a node in the TreeView is selected
  2. gets Disabled when a node in the TreeView loses focus

My Form have two TreeViews:

  1. TreeView containing Books
  2. TreeView containing Loans

and when one of them has the current selection I want the other to de-select its item.

I also have a ComboBox in the Form.

When the TreeView with Loan(s) has an item selected I want to press a button to return this loan. But as soon as I try to press the button it gets disabled and I cannot interact with it.

I have tried to solve it like this:

private void treeViewLoans_AfterSelect(object sender, TreeViewEventArgs e)
{
    ReturnLoanButtonCheck();
}

private void treeViewLoans_Leave(object sender, EventArgs e)
{
    treeViewLoans.SelectedNode = null;
    ReturnLoanButtonCheck();
}

private void ReturnLoanButtonCheck()
{
    if (treeViewLoans.SelectedNode == null)
        buttonReturnLoan.Enabled = false;
    else if (treeViewLoans.SelectedNode != null)
        buttonReturnLoan.Enabled = true;
}

When I try to press the button the ComboBox gets focus instead.

What am I doing wrong here?

Upvotes: 0

Views: 320

Answers (1)

Ben Steele
Ben Steele

Reputation: 414

You could add the Button the treeview as a child like the following:

<Window x:Class="TreeDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TreeDemo"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="172*"/>
        <ColumnDefinition Width="345*"/>
    </Grid.ColumnDefinitions>
    <TreeView>
        <TreeViewItem Header="Item 1">
            <Label Content="Invoce 1"/>
            <Button Content="Test 1" />
        </TreeViewItem>
        <TreeViewItem Header="Item 2">
            <Label Content="Invoce 2"/>
            <Button Content="Test2" />
        </TreeViewItem>
        <TreeViewItem Header="Item 3">
            <Label Content="Invoce 3"/>
            <Button Content="Test 3" />
        </TreeViewItem>
        <TreeViewItem Header="Item 3">
            <Label Content="Invoce 3"/>
            <Button Content="Test 3" />
        </TreeViewItem>
        <TreeViewItem Header="Item 3">
            <Label Content="Invoce 3"/>
            <Button Content="Test 3" />
        </TreeViewItem>
    </TreeView>
</Grid>

Upvotes: 1

Related Questions