【发布时间】:2012-04-11 08:53:56
【问题描述】:
我是 WPF 数据绑定/样式/模板的新手... 我正在尝试使用样式将一组属性值应用于按钮。样式绑定到类的字段。如您所见,这对于 BackColor 属性非常有效。但是当我尝试设置 TextBlock 的文本时,它不起作用(我也没有收到绑定错误)。我的最终目标是也能够将图像设置为内容。
当我不使用 DataTemplate 并使用 SetterProperty="Content" 而不是“ContentTemplate”时,它适用于一个按钮,但是当添加第二个按钮时,它会给我一个运行时错误“指定的元素已经是合乎逻辑的另一个元素的子元素。先断开它。”
我在这里缺少什么?我在 "TextBlock Text="???" 中放入什么
顺便说一句。一旦它工作,我想将样式移动到全局范围,所以我不想使用任何明确引用 MyClass 的东西
<Window.Resources>
<Style TargetType="Button" x:Key="MyStyle">
<Setter Property="Background" Value="{Binding BackColor}"/>
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="XYZ-"/>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel Orientation="Horizontal" Height="30">
<Button Style="{StaticResource MyStyle}" DataContext="{Binding Action1}"/>
<Button Style="{StaticResource MyStyle}" DataContext="{Binding Action1}"/>
<Button Style="{StaticResource MyStyle}" DataContext="{Binding Action2}"/>
<Button Style="{StaticResource MyStyle}" DataContext="{Binding Action2}"/>
</StackPanel>
和
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
Action1 = new MyClass() { Text = "ACTION1", BackColor = new SolidColorBrush(Colors.Red) };
Action2 = new MyClass() { Text = "ACTION2", BackColor = new SolidColorBrush(Colors.Green) };
}
public MyClass Action1{get; private set;}
public MyClass Action2{get; private set;}
}
public class MyClass
{
public string Text { get; set; }
public Brush BackColor { get; set; }
}
【问题讨论】:
标签: c# .net wpf templates binding