Reputation: 129
I want to get my grid disabled when my property is Null and enabled when is Not null.
In my .XAML :
<Grid Grid.Row="2" IsEnabled="{Binding ElementName=dgCustomers, Path=SelectedItem}">
<my:ProductsHistoryDetailView />
</Grid>
In my ViewModel.cs :
public ProductHistory SelectedItem
{
get { return _SelectedItem; }
set
{
if (_SelectedItem != value)
{
_SelectedItem = value;
RaisePropertyChanged(() => SelectedItem);
}
}
}
Upvotes: 0
Views: 11368
Reputation: 4040
You should add an extra property to your viewmodel.
public bool IsGridEnabled
{
get
{
return this.SelectedItem != null;
}
}
<Grid Grid.Row="2" IsEnabled="{Binding IsGridEnabled}">
<my:ProductsHistoryDetailView />
</Grid>
And when your SelectedItem
changes, call the OnPropertyChanged event for IsGridEnabled
:
public ProductHistory SelectedItem
{
get { return _SelectedItem; }
set
{
if (_SelectedItem != value)
{
_SelectedItem = value;
RaisePropertyChanged(() => SelectedItem);
RaisePropertyChanged(() => IsGridEnabled);
}
}
}
Upvotes: 7
Reputation: 841
Use a Style Trigger to change the Enabled Property instead of trying to bind it directly
<Grid Grid.Row="2">
<Grid.Style>
<Style TargetType="Grid">
<Setter Property="IsEnabled" Value="True"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=dgCustomers, Path=SelectedItem"}" Value={x:Null}>
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
</Grid>
Upvotes: 4
Reputation: 102793
You could use an IValueConverter
:
<Grid Grid.Row="2" IsEnabled="{Binding
ElementName=dgCustomers, Path=SelectedItem,
Converter={StaticResource NullToFalseConverter}">
public class NullToFalseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? false : true;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Alternatively, it might be easier to add another property IsSelected
to your view model, which you could bind directly to IsEnabled
:
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
_isSelected = value;
RaisePropertyChanged(() => IsSelected);
}
}
}
public ProductHistory SelectedItem
{
get { return _SelectedItem; }
set
{
if (_SelectedItem != value)
{
_SelectedItem = value;
RaisePropertyChanged(() => SelectedItem);
}
IsSelected = value != null;
}
}
Upvotes: 2
Reputation: 3967
Please make sure your selectebitem has a valid value like this:
<Grid Grid.Row="2" IsEnabled="{Binding ElementName=dgCustomers, Path=SelectedItem.Value}">
<my:ProductsHistoryDetailView />
</Grid>
Upvotes: 1