您試圖使用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>
你在問如何讀取文本文件,而你的示例代碼是一個按鈕的事件處理程序。請提供讀取文件的代碼。 –
是的,我想要創建的按鈕來使用該事件處理程序。我更新了讀取文件的代碼。 – proah
@MarioStoilov隨着我的進步再次更新了一次。 – proah