xaml中的条件元素取决于绑定内容

Tho*_*lin 16 c# wpf xaml binding

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

 <TextBlock Text="{Binding Path=Address}" />
Run Code Online (Sandbox Code Playgroud)

Don*_*nut 22

基本上,您需要编写一个,IValueConverter以便您可以将您的Visibility属性绑定TextBoxAddress字段或您创建的新字段.

如果你绑定到Address字段,这里的绑定可能是这样的::

<TextBlock Text="{Binding Path=Address}"
    Visibility="{Binding Path=Address, Converter={StaticResource StringLengthVisibilityConverter}}" />
Run Code Online (Sandbox Code Playgroud)

然后StringLengthVisiblityConverter看起来像这样:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<src:StringLengthVisiblityConverter x:Key="StringLengthVisiblityConverter" />
Run Code Online (Sandbox Code Playgroud)


dev*_*tal 7

我会与另一个叫布尔属性做到这一点HasAddress,它返回Address.Length > 0.

<!-- In some resources section -->
<BooleanToVisibilityConverter x:Key="Bool2VisibilityConverter" />

<TextBlock 
  Text="{Binding Address}" 
  Visibility="{Binding HasAddress, Converter={StaticResource Bool2VisibilityConverter}}" 
/>
Run Code Online (Sandbox Code Playgroud)

您还应该记得HasAddress在setter中通知属性更改Address.