Wpf how to relate to the existence of a DataContext?

I am setting a dynamic datacontext file in code. I would like the button on the screen to be on / off depending on whether DataContext == null or not. I can do this in code when I assign a DataContext, but it would be better if I could get so attached :)

+8
c # wpf binding datacontext
source share
2 answers

You can use a DataTrigger -style DataTrigger to disable your button when the DataContext is null. Another option is to bind the IsEnabled property to the DataContext and use the value converter to return false if the DataContext is null and true otherwise.

With trigger:

 <Button> <Button.Style> <Style TargetType="{x:Type Button}"> <Style.Triggers> <DataTrigger Binding="{Binding Path=DataContext, RelativeSource={RelativeSource Self}}" Value="{x:Null}"> <Setter Property="IsEnabled" Value="false"/> </DataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> 

With converter:

Converter

 public class DataContextSetConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value != null; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 

And use it

 <UserControl.Resources> <local:DataContextSetConverter x:Key="dataContextSetConverter"/> </UserControl.Resources> ... <Button IsEnabled="{Binding Path=DataContext, RelativeSource={RelativeSource Self}, Converter={StaticResource dataContextSetConverter}}"/> 
+13
source share

This should do it:

  <Button Content="ButtonName"> <Button.Style> <Style TargetType="{x:Type Button}"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=DataContext}" Value="{x:Null}"> <Setter Property="Visibility" Value="Collapsed" /> </DataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> 
+4
source share

All Articles