2016-10-08 22 views
0

我是WPF中的新手,現在我嘗試了幾天。C#WPF將worker.cs中的工作人員信息推送到Home.xaml

在我的MainWindow.xaml.cs中,我創建了一個新的工作實例。

public MainWindow() 
    { 
     InitializeComponent(); 
     Worker worker = new Worker(); 
     worker.run_Worker(); 
    } 

的MainWindow.xaml加載Home.xaml在啓動時:

ContentSource = 「/頁/ Home.xaml」

在我Home.xaml我有一個進度條和信息日誌。

在工體我想是這樣的:

Home home = new Home(); 
Dispatcher.BeginInvoke(new Action(() => 
{ 
     home.InfoLog.Content = "test"; 
})); 

Ihis工作,如果我把爲職工代碼到Home.xaml.cs但如果把工人的分離式類和推數據轉化爲新的家庭實例。

有沒有辦法將信息推送到不同的類/頁面,而不使用新的Home()實例?

謝謝:)

+0

你可以通過'this'成新工人( )並將其作爲工人的私有財產。所以:'public MainWindow() { InitializeComponent(); Worker worker = new Worker(this); worker.run_Worker(); }' 'class Worker {0;}; set;} public Worker(MainWindow lthis){this.lthis = lthis; } }' 您還必須使用'Application.Current.Dispatcher'來調用任何UI更改。 – ajdrausal

+0

然後我可以爲工作人員提供MainWindow。但是Home()呢?有顯示工作進度的元素。我仍然無法以這種方式訪問​​它們。或meybee我沒有understsand你:) – Cluster2a

+0

你需要添加一個x:名稱在你的MainWindow.xaml元素代表''像那麼你將能夠從後面的代碼訪問該元素。我在下面添加了一些代碼。 – ajdrausal

回答

0

你可以通過「本」到新的工作(),並使其職工的私有財產。 所以:

UI

<Window x:Class="testappreddit.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:local="clr-namespace:testappreddit" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
Title="MainWindow" 
Width="525" 
Height="350" 
DataContext="{Binding RelativeSource={RelativeSource Self}}" 
mc:Ignorable="d"> 
<Grid> 
<StackPanel> 
    <Home x:Name="home" /> 

</StackPanel> 
</Grid> 
</Window> 

後端

public class MainWindow{ 

    public MainWindow() 
    { 
     InitializeComponent(); 
     Worker worker = new Worker(this); 
     worker.run_Worker(); 
    } 
} 

public class Worker 
{ 
private MainWindow lthis{get;set;} 
public Worker(MainWindow lthis) 
{ 
    this.lthis = lthis; 
} 
public void run_worker(){ 
    while(lthis != default(MainWindow)){ 
     DoWork(); 
     Thread.Sleep(5000); 

    } 
} 
private void DoWork(){ 
    Application.Current.Dispatcher.BeginInvoke(new Action(() => 
     { 
      lthis.home.InfoLog.Content = "test"; 
     })); 
    } 

} 

public class Home 
{ 
    public InfoLog InfoLog {get;set;} 

} 

public class InfoLog 
{ 
    public string Content {get;set;} 
} 

你也將不得不使用

Application.Current.Dispatcher 

調用任何UI改變