Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

mvvm

wpf

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?

like image 859
Joe.Net Avatar asked Apr 08 '11 22:04

Joe.Net


1 Answers

Check if your solution is like that: View:

<Window x:Class="WpfApplication13.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:vm="clr-namespace:WpfApplication13"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <vm:MainVM/>
    </Window.DataContext>
    <Grid>
        <TextBlock Text="{Binding Path=FullName, Mode=OneWay}" 
                   Foreground="{Binding Path=ForegroundColor}"
                   Margin="0 5 3 5"/>
    </Grid>
</Window>

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;

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

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

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

Running app

and remember that if you want to set new value for ForegroundColor in VM you sholud do it like that:

ForegroundColor = System.Windows.Media.Brushes.Red;

to raise PropertyChangedEvent

Accordind to new information about your problem, you could try this solution:

CustomerHeaderViewModel.cs

class CustomerHeaderViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Customer> Customers { get; set; }

    public void LoadCustomers()
    {
        ObservableCollection<Customer> customers = new ObservableCollection<Customer>();

        //this is where you would actually call your service
        customers.Add(new Customer { FirstName = "Jim", LastName = "Smith", NumberOfContracts = 23 });
        customers.Add(new Customer { FirstName = "Jane", LastName = "Smith", NumberOfContracts = 22 });
        customers.Add(new Customer { FirstName = "John", LastName = "Tester", NumberOfContracts = 33 });
        customers.Add(new Customer { FirstName = "Robert", LastName = "Smith", NumberOfContracts = 2 });
        customers.Add(new Customer { FirstName = "Hank", LastName = "Jobs", NumberOfContracts = 5 });

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

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

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

CustomerHeaderView.xaml

<UserControl x:Class="TestMvvm444.Views.CustomerHeaderView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="main">
    <Grid>
        <StackPanel HorizontalAlignment="Left">
            <ItemsControl ItemsSource="{Binding Path=Customers}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <StackPanel Orientation="Horizontal">
                                <TextBox
                                Text="{Binding Path=FirstName, Mode=TwoWay}" 
                                Width="100" 
                                Margin="3 5 3 5"/>
                                <TextBox 
                                Text="{Binding Path=LastName, Mode=TwoWay}" 
                                Width="100"
                                Margin="0 5 3 5"/>
                                <TextBlock 
                                Text="{Binding Path=FullName, Mode=OneWay}" 
                                Foreground="{Binding ElementName=main, Path=DataContext.ForegroundColor}"
                                Margin="0 5 3 5"/>
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>
    </Grid>
</UserControl>

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:

<TextBlock 
    Text="{Binding Path=FullName, Mode=OneWay}"
    Foreground="{Binding RelativeSource={RelativeSource FindAncestor,
    AncestorType={x:Type UserControl}}, Path=DataContext.ForegroundColor}"
    Margin="0 5 3 5"/>

Remember that DataContext of this control was set earlier in MainWindow.cs.

MainWindow.cs

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        CustomerHeaderViewModel customerHeaderViewModel = new CustomerHeaderViewModel();
        customerHeaderViewModel.LoadCustomers();
        CustomerHeaderView.DataContext = customerHeaderViewModel;
    }
}

App

like image 108
PawelSt Avatar answered Oct 14 '22 05:10

PawelSt