gpt4 book ai didi

wpf - 绑定(bind)到 WPF ViewModel 属性

转载 作者:行者123 更新时间:2023-12-03 11:00:56 25 4
gpt4 key购买 nike

我只是在玩 WPF 和 MVVM,我制作了一个简单的应用程序,它显示一个 Rectangle,只要网络可用性发生变化,它就会改变颜色。

但是当这种情况发生时,我会收到这个错误: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 属性?

最佳答案

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

有点像这样:

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

有一个 MSDN article here有更多信息。

关于wpf - 绑定(bind)到 WPF ViewModel 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2522830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com