定义两个参数&将值从一个方法传递到另一个方法
本文关键字:方法 一个 另一个 两个 参数 定义 | 更新日期: 2023-09-27 18:03:55
如何将值从一个方法传递到另一个方法?我为我在c#方面的知识不足而道歉。到目前为止我所做的都不起作用。我希望将值'MaxHeight'从Page()传递到'MaxHeight'从fullNameControlLoaded()。
Page.xaml.cs:
public Page(string _setArticles, string _setLength)
{
InitializeComponent();
//testing!
//send value to method 'fullNameControl_Loaded' (summary length of each ListBox item)
int MaxHeight = 0;
if (!string.IsNullOrEmpty(_setLength))
{
if (_setLength.Contains("_3"))
MaxHeight = 30;
fullNameControl_Loaded(null, null, MaxHeight);
}
}
private TextBlock m_textBlock;
void fullNameControl_Loaded(object sender, RoutedEventArgs e, int MaxHeight)
{
m_textBlock = sender as TextBlock;
m_textBlock.MaxHeight = MaxHeight;
}
你还没有弄清楚什么不工作,但是这个:
if (_setLength.Contains("_3"))
MaxHeight = 30;
fullNameControl_Loaded(null, null, MaxHeight);
看起来应该是这样的:
if (_setLength.Contains("_3"))
{
MaxHeight = 30;
fullNameControl_Loaded(null, null, MaxHeight);
}
然而,此时sender
将为空,因此fullNameControl_Loaded()
将抛出NullReferenceException
。
似乎不太可能您真的想要改变方法中m_textBlock
的值…你希望在哪里初始化它?
这不是这样做的,在类范围内声明您的MaxHeight
字段,然后您可以从类内的任何地方访问它。请勿修改生成的事件
你可以设置"MaxHeight"作为一个属性在你的类,然后页面构造器可以设置它的值,然后当fullNameControl_Loaded函数运行时,属性的值将从页面构造器更新的值。
private int maxHeight = 0;公共页面(字符串_setArticles,字符串_setLength){
InitializeComponent (); //testing!!!!
//send value to method 'fullNameControl_Loaded'
//(summary length of each ListBox item)
maxHeight = 0;
if (!string.IsNullOrEmpty(_setLength))
{
if (_setLength.Contains("_3"))
maxHeight = 30;
fullNameControl_Loaded(m_textBlock, null, MaxHeight);
}
}
private TextBlock m_textBlock;
void fullNameControl_Loaded(object sender, RoutedEventArgs e, int MaxHeight)
{
m_textBlock = sender as TextBlock;
m_textBlock.MaxHeight = maxHeight;
}