2011-12-28 6 views
0

私にはUser Interfaceがあり、メイングリッドのbackgroundプロパティを変更しています。今やいくつかは非常に愉快な表情をしますが、表示されているテキストを読むのが難しいものもあります。しかし、私は約20のラベルをそこに持っているときに問題が発生し、それらを変更して色を割り当てるたびにコードが醜く見えるようになります。私はよりエレガントなデザインが必要であることを知っています。バインドラベル変数への前景

ラベルを色にバインドしようとしましたが、動作しません。ここにコードがある

XAML:

<Label Foreground="{Binding defColor}" Content="Settings" Height="44" HorizontalAlignment="Left" Margin="12,53,0,0" Name="label1" VerticalAlignment="Top" FontWeight="Normal" FontSize="26" /> 

コードの背後にある:

​​

おかげ

+0

重複がありますか? http://stackoverflow.com/questions/6186344/style-to-choose-suitable-foreground-according-to-background-color – Josh

+0

エラーメッセージを詳しく説明できますか? –

+0

エラーメッセージが表示されず、色が更新されない可能性があります( –

答えて

1

あなたはこの= SettingsWindowのDataContextを設定している場合は、あなたが結合してSettingsWindowクラスはINotifyPropertyChangedを実装しなければならない(MUST)。 {Binding defColor}が機能するようにします。必要なコード:

public class SettingsWindow : Window, INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    public SettingsWindow() 
    { 
     // We are acting as our own 'ViewModel' 
     DataContext = this; 
     InitializeComponent(); 
    } 

    private Color _defColor; 
    public Color defColor 
    { 
     get { return _defColor; } 
     set 
     { 
      if (_defColor != value) 
      { 
       _defColor = value; 
       if(null != PropertyChanged) 
       { 
        PropertyChanged(this, "defColor"); 
       } 
      } 
     } 
    } 
} 

アプリケーション内のすべてのラベルを対象とする場合、適切な方法は、前述のようにスタイルを使用することです。 このスタイルは各ラベルに適用する必要があります。 x:Keyを省略して、ラベルのデフォルトのスタイルにします。

<Style x:Key="LabelForeGroundStyle" TargetType="{x:Type Label}"> 
     <Setter Property="Foreground" Value="{Binding defColor}" /> 
    </Style> 
2

ちょうどあなたが掲示C#のコードを見てから、私はあなたの最初の問題はあると思いますその」これを行った

SolidColorBrush defColor = new SolidColorBrush(); 

の代わりに

public SolidColoRBrush defColor { get; set; } 

プロパティにのみバインドできます。

あなたのコンストラクタは、今、私は、あなたがstyleを使うべきだと思う同じプロパティに各ラベルを結合させる代わりに、この

public SettingsWindow() 
{ 
    InitializeComponent(); 
    defColor = new SolidColorBrush(Colors.Black); 
    this.DataContext = this; // need to tell your window where to look for binding targets 
} 
+0

こんにちは。これは変更されましたが、まだ動作しません:( –

1

ようになり、それぞれのラベル、例えばのためにこのスタイルを適用します

trigger
<Style x:Key="LabelForeGroundStyle" TargetType="{x:Type Label}"> 
    <Setter Property="Foreground" Value="{Binding defColor}" /> 
    </Style> 

またはより良い、:;

<Style.Triggers> 
<Trigger> 
    <Trigger Property="Background" Value="Blue"> 
    <Setter Property="Foreground" Value="Green"/> 
    </Trigger> 
</Trigger> 
</Style.Triggers> 
+0

まだ動作しません。 –

関連する問題