如何... if语句和按钮内容“WP7”

时间:2011-12-09 22:48:03

标签: c# windows-phone-7

这样做的正确方法是什么?这种方式不起作用:

if (((String)enterAmountButton.Content) == "")
 MessageBox.Show("Please enter the total bill amount.");
else if (((String)enterTipButton.Content) == "")
 MessageBox.Show("Please enter the tip % amount.");   

这种方式既不起作用:

if (enterAmountButton.Content == "")   
 MessageBox.Show("Please enter the total bill amount.");   
else if (enterTipButton.Content == "")   
 MessageBox.Show("Please enter the tip % amount.");   

3 个答案:

答案 0 :(得分:0)

if ((string)(enterAmountButton.Content) == "")   
 MessageBox.Show("Please enter the total bill amount.");   
else if ((string)(enterTipButton.Content) == "")   
 MessageBox.Show("Please enter the tip % amount."); 

或者

if (enterAmountButton.Content.ToString() == "")   
 MessageBox.Show("Please enter the total bill amount.");   
else if (enterTipButton.Content.ToString() == "")   
 MessageBox.Show("Please enter the tip % amount."); 

答案 1 :(得分:0)

尝试这样的事情:

if(enterAmountButton.Content.ToString().Trim() == String.Empty)   
 MessageBox.Show("Please enter the total bill amount.");   
else if (enterTipButton.Content.ToString().Trim() == String.Empty)   
 MessageBox.Show("Please enter the tip % amount.");  

Trim()确保没有任何前导或尾随空格。也许这就是为什么你的第一次尝试不起作用?

答案 2 :(得分:-1)

var amountButtonString = enterAmountButton.Content as string;
        var enterTipButtonString = enterTipButton.Content as string;
        if (String.IsNullOrEmpty(amountButtonString))
            MessageBox.Show("Please enter the total bill amount.");
        else if (String.IsNullOrEmpty(enterTipButtonString))
            MessageBox.Show("Please enter the tip % amount.");  

会奏效。但是,你期望得到这些字符串?你很可能想要按钮旁边的TextBox中的值,对吗?

在那种情况下:

if (String.IsNullOrEmpty(amountTextBox.Text))
                MessageBox.Show("Please enter the total bill amount.");
            else if (String.IsNullOrEmpty(tipTextBox.Text))
                MessageBox.Show("Please enter the tip % amount.");  

amountTextBox& tipTextBoxx:Name的{​​{1}}。

最后一件事:

可能有更好的方法来解决这个问题。例如,如果您处理KeyUp& TextBox上的TextChanged事件,仅在文本存在时启用按钮(更好,有效的文本;))

您也可以使用转换器:

TextBoxes

添加对转化器public class StringToEnabledConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var val = value as string; if (val == null) throw new ArgumentException("value must be a string."); return !string.IsNullOrEmpty(val); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } #endregion }

的引用

并按下按钮,

<Converters:StringToEnabledConverter x:Key="StringToEnabledConverter" />