我想在按下按钮并且按钮正在运行其进程后,在主窗口中包含一个进度条。我知道我只是缺少一些简单的东西,但我仍然对WPF不熟悉,因为我主要使用Windows窗体。如何使用WPF中的progressBar
我的XML结构如下:
<Window x:Class="Program1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Program1"
mc:Ignorable="d"
Title="Program1" Height="1029" Width="1300" SnapsToDevicePixels="True" BorderThickness="0" Margin="0" ResizeMode="NoResize" Closing="Window_Closing"
x:Name="FirstWindow">
<Grid x:Name="Grid1">
<Button x:Name="btnPopulate" Content="Populate" HorizontalAlignment="Left" Margin="243,66,0,0" VerticalAlignment="Top" Width="118" Height="29" Click="btnPopulate_Click"/>
<Button x:Name="btnClear" Content="Clear" HorizontalAlignment="Left" Margin="366,66,0,0" VerticalAlignment="Top" Width="118" Height="29" Click="btnClear_Click"/>
<ProgressBar x:Name="progressBar" HorizontalAlignment="Left" Height="30" Margin="10,943,0,0" VerticalAlignment="Top" Width="351"/>
</Grid>
</Window>
我有我的填入按钮单击方法如下:
private void btnPopulate_Click(object sender, RoutedEventArgs e)
{
Thread backgroundThread = new Thread(
new ThreadStart(() =>
{
for (int n = 0; n < 100; n++)
{
Thread.Sleep(50);
progressBar.Value = n;
};
}
));
backgroundThread.Start();
}
我现在面临的问题是,我收到此错误:
The name 'progressBar' does not exist in the current context
我不确定如何从我的按钮单击方法访问progressBar控件。
我知道我很可能错过了一些简单的东西,但我仍然试图获得WPF的窍门。
首先,标记为XAML(这理所当然的,在技术上是XML)。您还应该调查使用MVVM模式;像WinForms一样使用WPF是一种快速的痛苦方式。 – BradleyDotNET
您不能使用WPF控件从一个线程以外的线程创建它们。 (通常是UI线程)所以你在做什么都行不通。 –
@BrandonKramer是正确的;如果你通过绑定更新你会没事的(那些自动编组到UI线程)。你也可以使用'Dispatcher.BeginInvoke'编组到UI线程 – BradleyDotNET