wpf how to bind to DataContext existence?

别说谁变了你拦得住时间么 提交于 2019-12-08 15:53:33

问题


I set the datacontext dynamically in code. I would like a button on screen to be enabled/disabled depending if DataContext == null or not. I can do it in code when I assign the DataContext but it would be better if I can bind like that :)


回答1:


You should be able to use a DataTrigger on the button style to disable your button when the DataContext is null. The other option is to bind the IsEnabled property to the DataContext and use a value converter to return false if 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}}"/>



回答2:


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>


来源:https://stackoverflow.com/questions/6313102/wpf-how-to-bind-to-datacontext-existence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!