我想在按下按鈕並且按鈕正在運行其進程後,在主窗口中包含一個進度條。我知道我只是缺少一些簡單的東西,但我仍然對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