WPF如何绑定到DataContext的所有脑干? [英] wpf how to bind to DataContext existance?
问题描述
我code动态设置的DataContext。我想在屏幕上的一个按钮来根据是否的DataContext == NULL
或不被启用/禁用。我能做到这一点在code,当我分配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 beter if I can bind like that :)
推荐答案
您应该能够使用 DataTrigger
按钮样式禁用按钮时的的DataContext
为空。另一种选择是将 IsEnabled
属性设置为的DataContext
并使用值转换器返回假
如果的DataContext
为空和真正
其他。
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屋!