2014-11-01 63 views
1

XAML:前景属性color

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

我必须做的,添加颜色Foreground财产在我的C#代码?

它使用这种方法:

SolidColorBrush bb = new SolidColorBrush(); 
+0

我重新格式化了您的问题。另外,我更新了你的标签 - 你在这里问一个特定的UI工具包(WPF),而你的代码隐藏的实际语言应该是相对不相关的。在任何情况下(即使这里与C#相关的事实都是相关的),应该在标签中而不是在问题标题中指明该语言。 – 2014-11-01 15:37:12

+2

有很多你没有告诉我们在这里。您是使用MVVM框架还是只是绑定到后面的代码?如果您使用视图模型,它是否实现了'INotifyPropertyChanged'?等等 – ChrisF 2014-11-01 15:38:58

回答

0

这是一个ViewModel工作方案,允许你通过改变自己的列表框选择改变文本框的颜色。

这是的.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> 

这是初始化和列表框后台代码:

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),然后使用get和可选的set方法为该值创建公共方法(在此例中为color)。绑定到公共实例(Foreground="{Binding color}")。在set中,您需要调用OnPropertyChanged("value")来通知绑定该值已更改。