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?
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 :
XAML (Edited to use the color picker, assuming the selected value of his control is named "SelectedValue" and that it returns a Brush object)
Check if your solution is like that: View:
ViewModel:
and remember that if you want to set new value for ForegroundColor in VM you sholud do it like that:
to raise PropertyChangedEvent
Accordind to new information about your problem, you could try this solution:
CustomerHeaderViewModel.cs
CustomerHeaderView.xaml
In presented scenario the ForegroundColor property resides in CustomerHeaderViewModel.cs so it is value for all customers. In CustomerHeaderView.xaml I added x:Name for UserControl to have a possiblity to refer to DataContext of this element. If you don't want to use x:Name for UserControl, you can try this:
Remember that DataContext of this control was set earlier in MainWindow.cs.
MainWindow.cs