繁体   English   中英

C#使用String.IsNullOrEmpty的结果设置标签的可见性

[英]C# Set the visibility of a label using the result of String.IsNullOrEmpty

嗨,我正在尝试基于文本框字符串为空设置标签的可见性。 我有以下代码:

MyLabel.Visible = String.IsNullOrEmpty(MyTextBox.Text);

文本框为空时,为什么MyLabel不出现?

更新

我尝试将这段代码放在文本框的Text_Changed事件中,但仍然无法正常工作。

这是一个更新问题,它确实适用于Text_Changed事件。 但是,问题在于在处理表单时触发它不起作用。

这是从我的控制器类触发的代码,可让所有人对正在发生的事情有更好的了解:

using (var frm = new frmAdd(PersonType.Carer))
{
    var res = frm.ShowDialog();
    if (res == System.Windows.Forms.DialogResult.OK)
    {
         if (frm.ValidateInformation())  // the above code is called in here
         {
               // process the information here...
         }
    }
}

我也忘了提到这种形式在类库项目(dll)中。

取决于代码在哪里运行。 如果需要交互性,即当在文本框中键入字符时标签消失,则需要在文本框的Keyup事件上运行它。 您可能还需要重新粉刷标签。

如果要在文本更改事件中更新Visible属性,则可能会遇到以下问题。 表单第一次启动时,文本将设置为空字符串。 但是因为这是初始值,所以它没有发生变化 ,因此不会引发任何事件。

您可能需要直接在Form构造函数中执行此更新。 查看是否可以解决问题。

我怀疑您想使用数据绑定来设置标签的可见性。
该讨论可能对您有所帮助: WPF数据绑定:基于var的内容启用/禁用控件?

更新,一些代码:

public string MyText
{
  get { return _myText; }
  set { _myText = value; OnPropertyChanged("MyText"); }
}

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
  if (PropertyChanged != null)
  {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
}

private void theTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
  _myText = theTextBox.Text;
  OnPropertyChanged("MyText");
}

}

[ValueConversion(typeof(string), typeof(System.Windows.Visibility))]
public class StringToVisibilityConverter : System.Windows.Data.IValueConverter
{
  public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    System.Windows.Visibility vis;
    string stringVal = (string)value;
    vis = (stringVal.Length < 1) ? Visibility.Visible : Visibility.Hidden;
    return vis;
  }

  public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    return null;
  }  
}
In the XAML:
<TextBlock Background="AliceBlue" >
  <TextBlock.Visibility>
    <Binding ElementName="window1" Path="MyText" Converter="{StaticResource stringToVisibilityConverter}"/>
  </TextBlock.Visibility>
</TextBlock>

我将添加一个Trim,以便在出现空格的情况下与User更一致:

MyLabel.Visible = String.IsNullOrEmpty(MyTextBox.Text.Trim());

剩下的事情就是在正确的时间触发代码。 如JaredPar所述,TextChanged应该涵盖除初始状态以外的所有内容。 尽管我将使用Form_Load,而不是构造函数。

澄清后进行编辑:
如果您的Label a TextBox位于frmAdd上,那么这个问题就没有意义了,ShowDialog返回后将不再显示表单本身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM