ConditionRacer
ConditionRacer

Reputation: 4498

How can I bind IsEnabled to whether or not a datagrid has a single item selected?

I have a DataGrid like this:

<DataGrid ItemsSource="{Binding MySource}" SelectedItem="{Binding SelectedItem}" />

And a tab control like this:

<TabControl IsEnabled="{Binding ???}" />

I want the TabControl to be enabled only when a single item is selected in the datagrid. If the selected item is null, or if there are multiple items selected, the tab control should be disabled.

Upvotes: 0

Views: 2164

Answers (2)

JSJ
JSJ

Reputation: 5691

I suggest you to use a converter and bind with element name proeprty as like below. \

Namespace

 xmlns:local="clr-namespace:WpfApplication1"

  <Window.Resources>
        <local:Enabledconverters x:Key="converter"/>
    </Window.Resources>



    <TextBlock  Name="textBlock1" Text="Sample Window"  VerticalAlignment="Center" HorizontalAlignment="Center" Grid.ColumnSpan="2" Margin="96,123" />
                <ListBox x:Name="list">

                </ListBox>
                <TabControl x:Name="tab" IsEnabled="{Binding SelectedItem,ElementName=list,Converter={StaticResource converter}}" Grid.Column="1">
                    <TabItem Header="Test"/>
                    <TabItem Header="Test"/>
                    <TabItem Header="Test"/>

                </TabControl>

Converter Code.

 public class Enabledconverters : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
                return true;

            return false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

Upvotes: 0

Kurubaran
Kurubaran

Reputation: 8902

Define a boolean property and bind it to your TabControl's IsEnabled attribute.

Within the SelectedItem property's Setter check if the selected item is null or item count is > 1 based on the condition set true or false to your tab control's IsEnabled binding property

Datagrid Binding:

<DataGrid ItemsSource="{Binding MySource}" SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

TabControl Binding:

<TabControl IsEnabled="{Binding IsTabEnabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

Datagrid's Selcted Item:

Public SelectedItem
{
get
{
}
set
{
if(null == SelectedItem || SelectedItem.count > 1)
IsTabEnabled = false;
}
}

Upvotes: 2

Related Questions