如何使TextBlock基于另一个TextBlock的绑定属性出现/消失?

时间:2012-03-18 00:05:16

标签: c# wpf xaml

假设我有两个TextBlock元素,一个是第二个元素的标签,它被绑定:

<TextBlock Margin="0,0,0,0" Text="Notes:" />
<TextBlock Margin="50,0,0,0" Text="{Binding Path=notes}" />

我只想在TextBoxes时出现这两个notes!="",只有在有东西要显示时才会出现。怎么会这样呢?

感谢。

2 个答案:

答案 0 :(得分:2)

这么多方法,DataTriggers,在ViewModel中执行逻辑,DependencyProp在代码后面,所以你可以通过绑定控制一切,没有任何触发器等。 或者这是仅在XAML中进行的示例。

复制/粘贴/运行此代码:

<Control>
        <Control.Style>
            <Style TargetType="Control">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Control">
                            <StackPanel x:Name="stackPanel">
                                <TextBlock Margin="0,0,0,0" Text="Notes:" />
                                <TextBlock x:Name="txtNotes" Margin="50,0,0,0" Text="{Binding Path=notes}" />
                            </StackPanel>
                            <ControlTemplate.Triggers>
                                <Trigger SourceName="txtNotes" Property="TextBlock.Text" Value="">
                                    <Setter TargetName="stackPanel" Property="Control.Visibility" Value="Collapsed"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Control.Style>
    </Control>

答案 1 :(得分:1)

首先创建一个转换器:

public class EmptyStringToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,
                          CultureInfo culture)
    {
        return string.IsNullOrEmpty(value as string)
                   ? Visibility.Collapsed
                   : Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, 
                              CultureInfo culture)
    {
        throw new InvalidOperationException();
    }
}

然后引用它(您可以在App资源,视图资源等中执行此操作:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Converters="clr-namespace:MyConverterNamespace">
  <Converters:EmptyStringToVisibilityConverter 
      x:Key="EmptyStringToVisibilityConverter"/>
</ResourceDictionary>

然后在您的控件中使用它:

<TextBlock Margin="0,0,0,0" Text="Notes:"
           Visibility="{Binding notes,
               Converter={StaticResource EmptyStringToVisibilityConverter}"/>
<TextBlock Margin="50,0,0,0" Text="{Binding Path=notes}"
           Visibility="{Binding notes,
               Converter={StaticResource EmptyStringToVisibilityConverter}"/>