2014-01-23 28 views
0

我想知道如何通過讀取.txt文件中的行來在我的Toolbar中創建按鈕。 例如:如何從.txt文件中的現有字符串創建多個按鈕

//bookmarks.txt 

http://example.com 
http://example2.com 
http://example3.com 
... 

我想的是,我在啓動程序應該在我創建的.txt每行按鍵與此事件:

public void Button_Click(object sender, RoutedEventArgs e) //fire bookmark event 
{ 
    string text = e.Source.ToString().Replace("System.Windows.Controls.Button: ", ""); 
    WebBrowser1.Navigate(text); 

} 

UPDATE

這我如何閱讀.txt文件:

for (int i = 0; i < File.ReadLines(@"bookmarks.txt").Count(); i++) 
{ 
     //Add button right here 
} 
+2

你在問如何讀取文本文件,而你的示例代碼是一個按鈕的事件處理程序。請提供讀取文件的代碼。 –

+0

是的,我想要創建的按鈕來使用該事件處理程序。我更新了讀取文件的代碼。 – proah

+0

@MarioStoilov隨着我的進步再次更新了一次。 – proah

回答

1

您試圖使用WPF,就好像它是WinForms一樣。這是你將如何履行WPF您的要求......先在Window代碼創建一個DependencyProperty系列背後和你的文本輸入來填充它:

public static DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(ObservableCollection<string>), typeof(YourWindowOrUserControl)); 

public ObservableCollection<string> Items 
{ 
    get { return (ObservableCollection<string>)GetValue(ItemsProperty); } 
    set { SetValue(ItemsProperty, value); } 
} 

... 

Items = new ObservableCollection<string>(File.ReadLines(@"bookmarks.txt")); 

然後你只是數據的收集綁定到ToolBar.ItemsSource財產和聲明DataTemplate來定義每個string應該是什麼樣子......你的情況,我們將其設置爲文本在Button

<ToolBar ItemsSource="{Binding Items}"> 
    <ToolBar.ItemTemplate> 
     <DataTemplate> 
      <Button Content="{Binding}" Margin="1,0,0,0" /> 
     </DataTemplate> 
    </ToolBar.ItemTemplate> 
</ToolBar> 

當然,你需要設置Window.DataContext到與你的公關課operties ......最簡單的方法是將其設置在後面的構造函數中的代碼是這樣的:

public YourWindowOrUserControl 
{ 
    InitializeComponent(); 
    DataContext = this; 
} 

必須關於如何設置DataContext雖然正確地讀了起來,因爲它設置這種方式很容易,但不一定是正確的。

最後,你可以創建一個爲Button所有必要屬性的類...例如,你可以添加一個名爲Text財產和另一個叫Command,然後讓你的Items財產的集合。然後你可以像這樣綁定數據:

<ToolBar ItemsSource="{Binding Items}"> 
    <ToolBar.ItemTemplate> 
     <DataTemplate> 
      <Button Content="{Binding Text}" Command="{Binding Command}" Margin="1,0,0,0" /> 
     </DataTemplate> 
    </ToolBar.ItemTemplate> 
</ToolBar> 
+0

非常好的答案。非常感謝你。 – proah

0

您可以創建動態按鈕並添加點擊事件:

Button btn = new Button(); 
btn.Location = new Point(yourX, yourY); 
btn.Font = new Font(btn.Font.Name, 10); 
btn.Text = "Text from your txt file here"; 
btn.ForeColor = Color.SeaShell; // choose color 
btn.AutoSize = true; 
btn.Click += (sender, eventArgs) => 
       { 
        string text = btn.Text.Replace("System.Windows.Controls.Button: ", ""); 
        WebBrowser1.Navigate(text); 
       }; 

(將此代碼插入您的For。順便說一句,你可以用while替換for。請參閱this鏈接)

相關問題