Alex Rivera | Logout

How can I bind Foreground to a property in my ViewModel?

Asked 2011-04-08T22:39:51.527
17

I would like to bind the foreground property of a TextBlock to a Property in my ViewModel.

This doesn't work :

Edit

View :

TextBlock 
Text="{Binding Path=FullName, Mode=OneWay}" 
Foreground="{Binding Path=ForegroundColor}"
Margin="0 5 3 5"

Code behind:

CustomerHeaderViewModel customerHeaderViewModel = new CustomerHeaderViewModel();
customerHeaderViewModel.LoadCustomers();
CustomerHeaderView.DataContext = customerHeaderViewModel;

View Model:

private System.Windows.Media.Brush _foregroundColor;
_foregroundColor = System.Windows.Media.Brushes.DarkSeaGreen;

public System.Windows.Media.Brush ForegroundColor
{
    get { return _foregroundColor; }
    set { _foregroundColor = value; 
        OnPropertyChanged("ForegroundColor");
    }
}

public CustomerHeaderViewModel()
{
ForegroundColor = System.Windows.Media.Brushes.Red;
}

All other properties (Text etc) correctly bind.

What am I doing wrong?

Edit
Report

1 Answer

4

This is not a good practice to put UI elements in your view model. Your view model must only encapsulate business locig.

If you want to change the color of anything in your UI that depends on on the value of your textbox, it's a better practice to use data triggers in XAML.

You can do like this :

Viewmodel :

public class MainVm : INotifyPropertyChanged
{
    protected void OnPropertyChanged(string porpName)
    {
        var temp = PropertyChanged;
        if (temp != null)
            temp(this, new PropertyChangedEventArgs(porpName));
    }
    public event PropertyChangedEventHandler PropertyChanged;

    public string FullName
    {
        get { return "Hello world"; }
    }
}

XAML (Edited to use the color picker, assuming the selected value of his control is named "SelectedValue" and that it returns a Brush object)

    <Grid>
    <TextBlock Text="{Binding Path=FullName, Mode=OneWay}" 
               Margin="0 5 3 5" Foreground="{Binding ElementName=colorpicker, Path=SelectedValue}"/>
    <ColorPicker x:Name="colorpicker"/>
</Grid>
answered 2011-04-09T08:25:49.637

Your Answer