2017-02-14 35 views
0

解決運行C#代碼時,按鈕在Blend的Visual Studio 2015年單擊

我一直在尋找了一段時間,所以我想它會幫助幾個人也找不到答案。

我發現blend是一個非常棒的地方,可以製作出漂亮的UI。

我已經在Blend從Visual Studio做了一個簡單button 2015年

這個按鈕的XAML看起來是這樣的:

<Window x:Class="WpfApplication1.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:WpfApplication1" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Button x:Name="button" Content="Button" Margin="56.471,79.283,54.639,68.382"/> 

    </Grid> 
</Window> 

和CS文件看起來像這樣:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 
using System.Net; 
using System.IO; 
namespace WpfApplication1 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void button_Click(object sender, RoutedEventArgs e) 
     { 
    WebRequest request =WebRequest.Create("http://www.example.com");  
    WebResponse response = request.GetResponse(); 
    Stream dataStream = response.GetResponseStream(); 
    StreamReader reader = new StreamReader(dataStream); 
    string responseFromServer = reader.ReadToEnd(); 
    MessageBox.Show(responseFromServer); 
     } 
    } 
} 

現在,當我點擊按鈕時,我喜歡它運行以下代碼來讀取URL(用C#編寫)

 WebRequest request = WebRequest.Create("http://www.example.com"); 
     WebResponse response = request.GetResponse(); 
     Stream dataStream = response.GetResponseStream(); 
     StreamReader reader = new StreamReader(dataStream); 
     string responseFromServer = reader.ReadToEnd(); 
     MessageBox.Show(responseFromServer); 

我在C#中很新,我不確定如何將代碼與XAML文件結合起來。

如果有人可以展示如何實現它將是非常棒的。

謝謝。

+1

的代碼,您應該簡單地可以只需更換'Console.WriteLine(「喲男子」);'你要運行的代碼,當按鈕按下。你有沒有嘗試過,或者有什麼理由爲什麼這不適合你? –

+0

嘿,隊友,對不起,這是我的代碼的一部分,只是爲了檢查我是否知道打印信息。我試圖插入readurl的東西,但即使在使用System.Net後,即使在'WebClient'上也有問題。 – Ben

+0

不需要道歉。你能編輯你的問題來包含插入你的WebClient代碼時可能遇到的任何編譯錯誤嗎? –

回答

0

也許我錯過了一些東西,但它似乎沒有連線。

<Grid> 
    <Button x:Name="button" Content="Button" Margin="56.471,79.283,54.639,68.382" Click="button_Click"/> 
</Grid> 

然後在後面

private void button_Click(object sender, RoutedEventArgs e) 
    { 
     using (WebClient client = new WebClient()) 
     { 
      string s = client.DownloadString(url); 
     } 
    } 
+0

佈線可能在'InitializeComponent'方法中由VS生成的代碼中處理。 –