<Grid>
<!--UserControl-->
<DragViewer x:Name="dragViewer"
Width="auto" Height="auto" />
</Grid>
WPF主窗体单例模式可以通过以下步骤实现:
在App.xaml.cs文件中重写OnStartup方法,在该方法中创建一个MainWindow实例,并将其设置为应用程序的主窗口;
在MainWindow.xaml.cs文件中重写OnSourceInitialized方法,在该方法中获取当前窗口的句柄,并将其设置为单例模式;
在MainWindow.xaml.cs文件中重写OnClosed方法,在该方法中释放当前窗口的句柄,以便下次重新创建窗口时可以正常显示;
在App.xaml.cs文件中重写OnActivated方法,在该方法中检查当前窗口是否已经存在,如果存在则将其显示出来,如果不存在则创建一个新的窗口。
按我说的做:1. 打开Visual Studio 2008(05也成),新建一个WPF项目(别忘了选.NET Framework 3.0)
2. 打开Window1.xaml,用下面的代码替换原有的:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
title="Window1" Height="300" Width="300">
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="输入: "/>
<TextBox Name="TbInput" Width="100px"/>
<Button Name="BtnCalc" Click="BtnCalc_Click">求平均值</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="平均值: "/>
<Label Name="LblResult" Foreground="Red" Width="100px">abc</Label>
</StackPanel>
</StackPanel>
</Window>
3. 为BtnCalc_Click事件添加逻辑,打开Window1.xaml.cs,添加:
private void BtnCalc_Click(object sender, RoutedEventArgs e)
{
string input = TbInput.Text.Trim()
if (!String.IsNullOrEmpty(input))
{
string[] rawDataSet = input.Split(", ".ToCharArray())
if (rawDataSet.Length != 5)
return
try
{
int i = 0
double sum = 0
for (i <rawDataSet.Lengthi++)
sum += Double.Parse(rawDataSet[i])
LblResult.Content = sum / i
}
catch (Exception ex)
{
MessageBox.Show(ex.Message)
}
}
}
4. 运行程序,在文本框中输入五个数,中间用空格或逗号分开,然后点计算平均值按钮,即可显示结果。
注意:如果编译没过,请到Window1.xaml中找到:
<Button Name="BtnCalc" Click="BtnCalc_Click">
然后,删掉Click="BtnCalc_Click",再键入Click=,按界面提示添加一个新的事件处理方法,最后粘贴进第3步中的代码(不包括方法签名)即可。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)