绑定到WPF ViewModel属性

时间:2010-03-26 11:24:44

标签: wpf mvvm

我正在玩WPF和MVVM,我制作了一个简单的应用程序,显示一个矩形,当网络可用性发生变化时,它会改变颜色。

但是当发生这种情况时,我收到此错误:Cannot use a DependencyObject that belongs to a different thread than its parent Freezable.

代码

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>

代码隐藏

使用System.Windows; 使用WpfApplication1.ViewModels;

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

视图模型

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));
        }
    }
}

我假设我应该通过调用某些东西来改变NetworkStatusColor属性吗?

2 个答案:

答案 0 :(得分:3)

你假设正确。这是您想要查看的Dispatcher类和.Invoke方法。

有点像这样:

if (this.Dispatcher.Thread != Thread.CurrentThread)
{
    this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(...your method...), any, params, here);
    return
}

有一个MSDN article here,其中包含更多信息。

答案 1 :(得分:0)

使用MVVM,您在处理调度时有几个选择。您可以向视图发送某种消息以让它为您调用操作,或者您可以创建某种您可以轻松模拟的抽象调度程序服务。

查看MVVM Light工具包,因为它包含一个可以使用/复制的简单调度程序服务。