Conditional element in xaml depending on the binding content

后端 未结 3 997
礼貌的吻别
礼貌的吻别 2020-12-29 07:09

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 pr

3条回答
  •  暖寄归人
    2020-12-29 07:51

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

    
    

    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):

    
    

提交回复
热议问题