ab_mundi
ab_mundi

Reputation: 53

How to use WPF Validation rules on a Listbox to enable a 'OK' button

I'm new with WPF and I have a problem. I want to enable a button only if en element of a Listbox is selected, otherwise it has to be disabled. I've tried with simple Validation Rule but it doesn't worked. Can anyone give me a hint? Ty

Upvotes: 0

Views: 556

Answers (1)

mm8
mm8

Reputation: 169420

You don't use a ValidationRule to enable a Button but you could use a Button style with a trigger that binds to the SelectedItem property of the ListBox and sets the IsEnabled property of the Button to false if the SelectedItem property of the ListBox returns a null reference, e.g.:

<ListBox x:Name="lb">
    <ListBoxItem>1</ListBoxItem>
    <ListBoxItem>2</ListBoxItem>
    <ListBoxItem>3</ListBoxItem>
</ListBox>

<Button Content="Button">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedItem, ElementName=lb}" Value="{x:Null}">
                    <Setter Property="IsEnabled" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Ok, this works well ty. But I've to enable the button when 2 conditions are satisfied (a textbox not empty and an item of the listbox selected). How can i do this?

You could add another trigger:

<ListBox x:Name="lb">
    <ListBoxItem>1</ListBoxItem>
    <ListBoxItem>2</ListBoxItem>
    <ListBoxItem>3</ListBoxItem>
</ListBox>

<TextBox x:Name="txt" />

<Button Content="Button">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedItem, ElementName=lb}" Value="{x:Null}">
                    <Setter Property="IsEnabled" Value="False" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Text.Length, ElementName=txt}" Value="0">
                    <Setter Property="IsEnabled" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Upvotes: 1

Related Questions