xaml 中的条件元素取决于绑定内容 [英] Conditional element in xaml depending on the binding content

查看:23
本文介绍了xaml 中的条件元素取决于绑定内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以显示此TextBlock,仅当Address.Length >0 ?我想直接在 xaml 中执行此操作,我知道我可以以编程方式放置所有控件

Is it possible to display this TextBlock, only if the Address.Length > 0 ? I'd like to do this directly into the xaml, I know I could put all my controls programmatically

 <TextBlock Text="{Binding Path=Address}" />

推荐答案

基本上,您将需要编写一个 IValueConverter 以便您可以绑定 TextBox<的 Visibility 属性/code> 到 Address 字段或您创建的新字段.

Basically, you're going to need to write an IValueConverter so that you can bind the Visibility property of your TextBox to either the Address field, or a new field that you create.

如果您绑定到 Address 字段,则绑定可能如下所示:

If you bind to the Address field, here's how the binding might look like::

<TextBlock Text="{Binding Path=Address}"
    Visibility="{Binding Path=Address, Converter={StaticResource StringLengthVisibilityConverter}}" />

然后 StringLengthVisiblityConverter 看起来像这样:

And then StringLengthVisiblityConverter could look something like this:

public class StringLengthVisiblityConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || value.ToString().Length == 0)
        {
            return Visibility.Collapsed;
        }
        else
        {
            return Visibility.Visible;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Don't need to implement this
    }
}

然后你只需要添加你的转换器作为资源,使用这样的语法(其中 src 映射到定义转换器的命名空间):

Then you'd just need to add your converter as a resource, using syntax like this (where src is mapped to the namespace where the converter is defined):

<src:StringLengthVisiblityConverter x:Key="StringLengthVisiblityConverter" />

这篇关于xaml 中的条件元素取决于绑定内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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