前景属性颜色

时间:2014-11-01 15:31:16

标签: wpf foreground

XAML:

<TextBlock Name="resultado" HorizontalAlignment="Center"
           Height="152" Margin="14,324,23,0" TextWrapping="Wrap"
           VerticalAlignment="Top" Width="419" TextAlignment="Center"
           FontSize="100" Foreground="{Binding Color}"/>

我需要做什么才能在我的C#代码中添加Foreground属性中的Color?

正在使用这种方法:

SolidColorBrush bb = new SolidColorBrush();

1 个答案:

答案 0 :(得分:0)

这是一个使用ViewModel的工作解决方案,允许您通过更改ListBox选择来更改TextBox颜色。

这是.xaml代码:

<Grid>
    <StackPanel>
        <TextBlock Foreground="{Binding color}" Text="This is a test." FontSize="50" HorizontalAlignment="Center"/>

        <ListBox SelectionChanged="ListBox_SelectionChanged" Name="ForegroundChooser">
            <ListBoxItem Content="Green"/>
            <ListBoxItem Content="Blue"/>
            <ListBoxItem Content="Red"/>
        </ListBox>
    </StackPanel>
</Grid>

这是初始化和ListBox代码隐藏:

public partial class MainWindow : Window
{
  VM data = new VM();

  public MainWindow()
  {
    InitializeComponent();

    ForegroundChooser.SelectedIndex = 0;
    this.DataContext = data;
  }

  private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    if (ForegroundChooser.SelectedIndex == 0) data.color = new SolidColorBrush(Colors.Green);
    if (ForegroundChooser.SelectedIndex == 1) data.color = new SolidColorBrush(Colors.Blue);
    if (ForegroundChooser.SelectedIndex == 2) data.color = new SolidColorBrush(Colors.Red);
  }
}

这是您的ViewModel类:

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WpfApplication1
{
  class VM : INotifyPropertyChanged
  {
    private SolidColorBrush _color;
    public SolidColorBrush color
    {
      get { return _color; }
      set
      {
        if (_color == value)
          return;
        else _color = value;
        OnPropertyChanged("color");
      }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null)
      {
        handler(this, new PropertyChangedEventArgs(propertyName));
      }
    }
  }
}

您需要做的是创建ViewModel类的实例并将.xaml DataContext设置为它。创建要绑定到的值的私有实例(例如_color),然后使用color创建该值的公共方法(在本例中为get),并可选择{ {1}}方法。绑定到公共实例(set)。在Foreground="{Binding color}"中,您需要调用set来通知绑定值已更改。

相关问题