2013-08-03 37 views
0

好吧,我爲Buttons做了一個新的樣式,我想在我的應用程序中使用它。一般的想法是有10個廣場Button其中我將有一個Image,並在此TextBlock下。 我的問題是,我想爲每個Button設置我的Image.Source和我的TextBlock.Text不同。 什麼即時通訊做是這樣的:WPF綁定新的按鈕模板的屬性

<ControlTemplate TargetType="{x:Type Button}"> 

<Border x:Name="Border" CornerRadius="5" BorderThickness="1" Background="Gray" BorderBrush="Orange"> 
    <Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="Auto"/> 
     <RowDefinition Height="*"/> 
    </Grid.RowDefinitions> 
     <Image Margin="0,5,0,0" Grid.Row="0" Width="25" Height="25" VerticalAlignment="Center" HorizontalAlignment="Center"/> 
    <TextBlock FontSize="12"/> 
    </Grid> 
</Border> 

我應該爲了利用我的風格像這樣怎麼辦?

<Button Style="{DynamicResource MenuButtons}" Text="????" x:Name="LiveB" Source="????" Click="Live_Click"/> 

在此先感謝。

+1

看看這個: http://stackoverflow.com/questions/2734825/custom-button-template-in-wpf 有你需要的所有:) –

回答

2

如果全部,你需要的是一個圖片和一些文字,就可以使用該按鈕的.Tag.Content使其工作(MIS):

<Style x:Key="MenuButtons" ... 

    ... 
    <ControlTemplate TargetType="{x:Type Button}" > 
     <Border x:Name="Border" CornerRadius="5" BorderThickness="1" Background="Gray" BorderBrush="Orange"> 
      <Grid> 
       <Grid.RowDefinitions> 
        <RowDefinition Height="Auto"/> 
        <RowDefinition Height="*"/> 
       </Grid.RowDefinitions> 
       <Image Width="25" Height="25" VerticalAlignment="Center" HorizontalAlignment="Center" 
         Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Tag}" /> 
       <TextBlock FontSize="12" Text="{TemplateBinding Content}" Grid.Row="1" /> 
      </Grid> 
     </Border> 
    </ControlTemplate> 
    ... 

..和則:

<Button Style="{DynamicResource MenuButtons}" x:Name="LiveB" 
     Content="MyText la la la..." Tag="http://programming.enthuses.me/1.png" 
     Click="Live_Click" /> 

如果您需要更多的自定義內容,你需要看看Konstantin Zhukov的評論和Attached Properties

(爲什麼你不能只使用"{TemplateBinding Tag}"代替"...{RelativeSource TemplatedParent}..."?我不知道,但TemplateBinding通常是一個非常脆弱的快捷方式,並不總是做它應該做的...)

+0

非常感謝。那就是訣竅。我檢查了你的答案,而不僅僅是因爲你是我所需要的。哈桑的答案也適用,但我更喜歡通過XAML進行綁定。 – oimitro

1

你需要做的是創造出一個類,它會DataContext的行動,按鈕

Class ButtonDataContext 
{ 
    public String TextBlockText {get;set;} 
    public String ImageSource {get;set;} 
} 

然後做

LiveB.DataContext = new ButtonDataContext(){TextBlockText = "text", ImageSource = "Image Path"};

在控制模板XAML

<Image Source="{Binding Path=ImageSource}" Margin="0,5,0,0" Grid.Row="0" Width="25" Height="25" VerticalAlignment="Center" HorizontalAlignment="Center"/> 
<TextBlock Text="{Binding Path=TextBlockText}" FontSize="12"/> 
+0

謝謝你的回答,這是非常有益的。但我想要做的是從XAML代碼設置ImageSource和TextBlockText,而不是使用C#。任何想法? – oimitro