WPF如何绑定到DataContext存在? [英] wpf how to bind to DataContext existence?
问题描述
我在代码中动态设置了数据上下文.我希望根据是否DataContext == null
启用/禁用屏幕上的按钮.当我分配DataContext时,我可以在代码中完成此操作,但如果可以像这样进行绑定,那就更好了:)
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 :)
推荐答案
当DataContext
为null时,您应该能够在按钮样式上使用DataTrigger
来禁用按钮.另一种选择是将IsEnabled
属性绑定到DataContext
,如果DataContext
为null,则使用值转换器返回false
,否则使用true
.
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.
带有触发器:
<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>
带有转换器:
转换器:
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();
}
}
并使用它
<UserControl.Resources>
<local:DataContextSetConverter x:Key="dataContextSetConverter"/>
</UserControl.Resources>
...
<Button IsEnabled="{Binding Path=DataContext, RelativeSource={RelativeSource Self}, Converter={StaticResource dataContextSetConverter}}"/>
这篇关于WPF如何绑定到DataContext存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!