根据不同的内容结合在XAML条件元素 [英] Conditional element in xaml depending on the binding content

查看:365
本文介绍了根据不同的内容结合在XAML条件元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能显示该TextBlock的,只有当 Address.Length> 0 ?我想这样做直接进入XAML中,我知道我可以把我所有的控制编程

 < TextBlock的文本={绑定路径=地址}/>


解决方案

基本上,你将需要编写一个<一个href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx\"><$c$c>IValueConverter这样就可以绑定能见度的财产你的文本框来无论是地址字段,或者您可以创建一个新的领域。

如果您绑定到地址字段,这里是如何的结合看起来像:

 &LT; TextBlock的文本={绑定路径=地址}
    能见度={绑定路径=地址,转换器= {StaticResource的StringLengthVisibilityConverter}/&GT;

然后 StringLengthVisiblityConverter 可能是这个样子:

 公共类StringLengthVisiblityConverter:的IValueConverter
{
    公共对象转换(对象的值,类型TARGETTYPE,对象参数,CultureInfo的文化)
    {
        如果(价值== NULL || value.ToString()。长度== 0)
        {
            返回Visibility.Collapsed;
        }
        其他
        {
            返回Visibility.Visible;
        }
    }    公共对象ConvertBack(对象的值,类型TARGETTYPE,对象参数,CultureInfo的文化)
    {
        //不需要实现这个
    }
}

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

 &LT; SRC:StringLengthVisiblityConverter X:键=StringLengthVisiblityConverter/&GT;

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}" />

解决方案

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.

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}" />

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
    }
}

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天全站免登陆