【问题标题】:WPF Binding Properties of a new Button Template新按钮模板的 WPF 绑定属性
【发布时间】:2013-08-04 20:07:20
【问题描述】:

好的,我为 Buttons 创建了一个新样式,我想在我的应用程序中使用它。一般的想法是有 10 个正方形 Button,其中我将有一个 Image,在此下方是一个 TextBlock。 我的问题是我想为每个Button 设置我的Image.Source 和我的TextBlock.Text 不同。 我在做什么:

<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"/>

提前致谢。

【问题讨论】:

标签: c# wpf templates button binding


【解决方案1】:

如果全部您需要的是一张图片和一些文字,您可以使用按钮的.Tag.Content 使其工作(错误):

<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 通常是一个非常脆弱的快捷方式,并不总是能做它应该做的事情...)

【讨论】:

  • 非常感谢。那成功了。我检查了您的答案而不是哈桑的答案,只是因为您的答案正是我所需要的。哈桑的回答也有效,但我更喜欢通过 XAML 进行绑定。
【解决方案2】:

你需要做的是创建一个类来充当按钮的 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"/>

【讨论】:

  • 感谢您的回答,这很有帮助。但我想要做的是从 XAML 代码而不是在 C# 中设置 ImageSource 和 TextBlockText。有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 2014-02-03
  • 2012-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多