0
我有一個StackPanel
我在其中添加了具有相同樣式的不同按鈕。我想改變的唯一的事情是每個按鈕內部的標籤文本。我所做的是創建Button,分配樣式並將其添加到Stackpanel。現在,我想要的是對相應對象的數據綁定。我讀了一篇關於Databinding的文章,但我沒有明白。帶樣式的數據綁定按鈕
風格:
<Style x:Key="EventListUIEventButtonStyle"
TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Name="EventListUIEventButtonGrid"
ShowGridLines="false"
Height="60px"
Margin="0,5,0,0">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="45px" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="40px" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0"
Grid.Column="2"
Grid.ColumnSpan="2"
Grid.RowSpan="1"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Foreground="white"
FontSize="16"
FontWeight="bold">
00:01:12
</Label>
<Label Name="EventListUIEventButtonLabel01" Grid.Row="0"
Grid.Column="1"
Grid.ColumnSpan="1"
Grid.RowSpan="2"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Margin="0 5 0 0"
Foreground="black"
FontSize="22"
FontWeight="bold">
Test
</Label>
<Label Grid.Row="2"
Grid.Column="1"
Grid.ColumnSpan="1"
Grid.RowSpan="1"
VerticalAlignment="Bottom"
HorizontalAlignment="Center"
Foreground="white"
FontSize="12">
Restaurant
</Label>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
C#代碼:
Button EventListUIEventButton = new Button();
EventListUIEventButton = new Button();
EventListUIEventButton.Style = (Style)MainWindow.FindResource("EventListUIEventButtonStyle");
EventListUIEventButton.Background = new SolidColorBrush(this.GetFunctionColor(Event.Function));
// Here i want to set the databinding (Databinding: corresponding Object)
this.StackPanel.Children.Add(EventListUIEventButton);
我建議你從一個簡單的例子開始,看看數據綁定如何工作。你開始有點大。 – MBen
也有什麼理由你在代碼中創建按鈕?它通常是更好地做他們在XAML – Charleh
http://stackoverflow.com/questions/11274402/binding-in-textblock-doesnt-work-in-wpf/11274438#comment14826300_11274438 這在我的數據的簡單示例結合 – Charleh