Binding to WPF ViewModel properties

Posted by MartinHN on Stack Overflow See other posts from Stack Overflow or by MartinHN
Published on 2010-03-26T11:24:44Z Indexed on 2010/03/26 11:43 UTC
Read the original article Hit count: 495

Filed under:
|

I'm just playing around with WPF and MVVM, and I have made a simple app that displays a Rectangle that changes color whenever Network availability changes.

But when that happens, I get this error: Cannot use a DependencyObject that belongs to a different thread than its parent Freezable.

Code

XAML

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="400" Width="600">
<DockPanel LastChildFill="True">
    <Rectangle x:Name="networkStatusRectangle" Width="200" Height="200" Fill="{Binding NetworkStatusColor}" />
</DockPanel>
</Window>

Code-behind

using System.Windows; using WpfApplication1.ViewModels;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            DataContext = new NetworkViewModel();
        }
    }
}

ViewModel

using System.ComponentModel;
using System.Net.NetworkInformation;
using System.Windows.Media;

namespace WpfApplication1.ViewModels
{
    public class NetworkViewModel : INotifyPropertyChanged
    {
        private Brush _NetworkStatusColor;

        public Brush NetworkStatusColor
        {
            get { return _NetworkStatusColor; }
            set
            {
                _NetworkStatusColor = value;
                NotifyOfPropertyChange("NetworkStatusColor");
            }
        }

        public NetworkViewModel()
        {
            NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
        }

        protected void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {
            if (e.IsAvailable)
            {
                this.NetworkStatusColor = new SolidColorBrush(Colors.Green);
            }
            else
            {
                this.NetworkStatusColor = new SolidColorBrush(Colors.Red);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        public void NotifyOfPropertyChange(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

I assume that I should change the NetworkStatusColor property by invoking something?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about mvvm