Reputation: 866
I have a DataGrid with 4 columns, the first two of them are bound to an object. The other two are button columns are made like this
<DataGridTemplateColumn MaxWidth="100" Header="Delete">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="BtnDelete" CommandParameter="{Binding Path=Id}" Content="Delete" Click="BtnDeleteEmployee_Click" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
My Datagrid has CanUserAddRows="True" which always generates an empty row in the bottom of the grid. However, I would like the two buttons on the bottom row to be disabled until the other rows have been filled. As it is now, I'm (of course) getting a nullreferenceexception when I click the button.
I guess a solution would be to bind the button's IsEnabled property to
id>0
But how to do this, I am not sure.
Upvotes: 1
Views: 3170
Reputation: 190
You can use style Trigger as below
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Visibility" Value="Visible"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Id}" Value="{x:Null}">
<Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
This example hide the button completly when the value of Id
is null. But same can be done with IsEnabled property to disable the button
Upvotes: 2
Reputation: 28325
One way to accomplish this is to bind the IsEnabled
property to the Id property and use a ValueConverter to retun True or False based on your criteria.
A value converter could look like this:
public class IdToEnabledConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value != null && (int)value > 0;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
and you reference it in your resources section:
<Grid.Resources>
<local:IdToEnabledConverter x:Key="IdToEnabledConverter"/>
</Grid.Resources>
And bind the IsEnabled
property:
<Button IsEnabled="{Binding Id, Converter={StaticResource IdToEnabledConverter}}"/>
Upvotes: 1
Reputation: 46
I suggest using MVVM pattern and Commands. If you use commands with button, it will automatically be disabled based on CanExecute() return value. So this is a place where you could check if id>0.
Some useful info about commands: http://relentlessdevelopment.wordpress.com/2010/03/30/simplified-mvvm-commanding-with-delegatecommand/
Upvotes: 1