将可见性绑定到 DataContext [英] Binding Visibility to DataContext

查看:34
本文介绍了将可见性绑定到 DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个值转换器,可以将 null 转换为 Visibility.Collapsed.现在我尝试在用户控件中使用它,以便在 DateContext 为 null 时整个控件会崩溃

I have a value converter that converts null to Visibility.Collapsed. Now I try to use it in a user control so that the whole control would collapse when it's DateContext is null

控件如下所示:

<UserControl x:Class="PhoneApp.Controls.Header"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Visibility="{Binding Converter={StaticResource ToVisibility}}"
    d:DesignHeight="150" d:DesignWidth="480"> <-- some body here -->

它是这样使用的

<my:Header DataContext="{Binding SectionHeader}"/>

其中 SectionHeader 是视图模型属性.

Where SectionHeader is a view model property.

我有一个类似的控件,我不绑定 DataContext 但一些自定义 DP 和那里的折叠工作正常.然而,在这个中,值转换器似乎只有在 SectionHeader != null 时才被调用.当它为空时,控件呈现为空子级.

I hava a similar control where I don't bind DataContext but some custom DP and the collapsing there works fine. However, in this one, the value converter seems to be called only when the SectionHeader != null. When it is null, the control is rendered with empty children.

我想过不在这里使用 DataContext,但使用它控制更清晰.

I thought about not using DataContext here but the control is much cleaner with it.

为什么绑定到 DataContext 不起作用?你有什么建议?

Why binding to DataContext doesn't work? What do you suggest?

推荐答案

在这种情况下,当 DataContext 为 null 时,绑定将使用 TargetNullValue 属性.所以只需设置 TargetNullValue=Collapsed 就可以了:

In this case, when DataContext is null, binding will use value specified in TargetNullValue property. So simply set TargetNullValue=Collapsed and you're good to go :

Visibility="{Binding TargetNullValue=Collapsed}"

参考:[如何将 TargetNullValue 设置为 Visibility.Collapsed in Binding]

这篇关于将可见性绑定到 DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆