WPFデータバインディング/スタイル/テンプレートを初めて使用しています... スタイルを使用してボタンにプロパティ値のセットを適用しようとしています。スタイルはクラスのフィールドにバインドされます。ご覧のとおり、これはBackColorプロパティで正常に機能します。しかし、TextBlockのTextを設定しようとすると、動作しません(どちらもバインディングエラーが発生します)。私の究極の目標は、コンテンツとしてイメージを設定できることです。スタイル内にあるWPF DataTemplateでバインディングを使用する方法
私はDataTemplateを使用せず、 "ContentTemplate"の代わりに "ContentTemplate"の代わりにSetterProperty = "Content"を使用すると1つのボタンで動作しますが、2番目のボタンを追加するとランタイムエラー "別の要素の論理的な子です。最初に切断してください。 "
私はここで何が欠けていますか?私はそれは私が明示的にMyClassの
を参照するものを使用したくない作品たら、私はグローバルスコープにスタイルを移動したいと思います。「のTextBlockテキスト=」???」ところでに何を入れてくださいあなたは今、あなたが使用する必要が
<Setter Property="Background" Value="{Binding BackColor}"/>
<Setter Property="Content" Value="{Binding Text}"/>
を必要
<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; }
}
感謝を次のようにのItemsControlを使用したほうが良いかもしれしかし。はい、これはうまくいきますが、私はコンテンツの下で目に見えるオブジェクトを持つ必要があります。これを明確にするためにコード例を編集しました。 – Night94
私の更新された回答は役に立ちましたか? – Phil
番号。相対ソースバインディングを使用すると、上記のコードと同じ結果が得られます。これは、あるボタンにスタイルを適用するときに機能しますが、複数のボタンを使用しても同じ例外が表示されます。「指定された要素は、すでに別の要素の論理的な子です。 – Night94