WPF: Binding Visibility by string contents

后端 未结 5 1087
孤城傲影
孤城傲影 2021-01-07 22:55

Ok, so here is my XAML:


If InstanceName is null or an

相关标签:
5条回答
  • 2021-01-07 23:40

    If you are inside a (Data-)Template you can use Triggers for that.

    Otherwise, the MVVM-Pattern or a ValueConverter will help you.

    0 讨论(0)
  • 2021-01-07 23:41
    <TextBlock Text="{Binding Path=InstanceName},FallbackValue={x:Null}"></TextBlock>
    

    Then add a DataTrigger to check the value is null and change visibility using Setter. This is the simple method which iam using.

    0 讨论(0)
  • 2021-01-07 23:47

    You could use a ValueConverter:

    <TextBlock 
         Visibility="{Binding InstanceName, Converter={local:StringNullOrEmptyToVisibilityConverter}}" 
         Text="{Binding InstanceName}"/>
    

    with the following codebehind:

    public class StringNullOrEmptyToVisibilityConverter : System.Windows.Markup.MarkupExtension, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return string.IsNullOrEmpty(value as string) 
                ? Visibility.Collapsed : Visibility.Visible;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
        public override object ProvideValue(IServiceProvider serviceProvider)
        {            
            return this;
        }
    }
    
    0 讨论(0)
  • 2021-01-07 23:47

    Ok, so this is close with PyBinding:

    <TextBlock Text="{Binding Path=InstanceName}" Visibility="{p:PyBinding BooleanToVisibility(IsNotNull($[.InstanceName]))}"  ></TextBlock>
    

    I need to replace IsNotNull with something that means IsNotNullOrEmpty, but I'm getting closer.

    0 讨论(0)
  • 2021-01-07 23:50

    By putting an extra property in your viewmodel that you can bind the Visibility attribute to:

    public class ViewModel
    {
       public string InstanceName {...}
       public Visibility InstanceVisibility 
       { 
          get 
          {
               return String.IsNullOrEmpty(InstanceName) ? Visibility.Collapsed : Visibility.Visible;
          }
    }
    
    0 讨论(0)
提交回复
热议问题