我有 ViewModel ,它具有一些功能。功能是通过按钮启动的,单击按钮时可以执行命令。
ViewModel.cs
class WindowViewModel : INotifyPropertyChanged
{
public WindowViewModel()
{
canExecute = true;
}
public ICommand ApplyKMMCommand //command for button click, works great, tested
{
get
{
return applyKMMCommand ?? (applyKMMCommand = new Commands.CommandHandler(() =>
ApplyKMMToNewImage(), canExecute));
}
}
private bool canExecute;
private ICommand applyKMMCommand;
public void ApplyKMMToNewImage()
{
ApplyKMM.Init(); //algorithm name
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public BitmapImage DisplayedImage //displaying image that i work with
{
get { return Bitmaps.Filepath; }
set { Bitmaps.Filepath = value; NotifyPropertyChanged(nameof(DisplayedImage)); }
}
}
现在,我的 ApplyKMM.Init()
class ApplyKMM
{
public static void Init()
{
Bitmaps.Filepath = //do some thing with it...
}
}
还有我的 Models.Bitmaps.cs
static public BitmapImage Filepath
{
get { return filepath; }
set { filepath = value; }
}
static private BitmapImage filepath{ get; set; }
问题是,当我使ApplyKMM.Init
绑定到View的Image
控件时,它们的值没有改变。
如果没有ApplyKMM
,我可以在ViewModel中完成以下操作:
DisplayedImage = //do things with bitmap...
然后,Image
出现在“视图更改”中(用该图像制作东西之后)。
您能告诉我如何通知ViewModel,来自模型的代码filepath
中的某个地方发生了更改吗?
编辑:
View
中的绑定看起来像标准绑定:
<Image Source="{Binding DisplayedImage}"/>
按钮单击也有效,我仅在Models->ApplyKMM->ViewModel
之间的通信有问题
EDIT2:
属性Filepath
存储在Models
文件夹中,而不是函数ApplyKMM
所在的文件夹中。查看我的编辑内容,我尝试做类似的事情:
Models -> ApplyKMM -> ViewModel
。从模型中,我得到Filepath
。然后,我使用另一个命名空间中的函数ApplyKMM
。然后,用ApplyKMM
函数处理位图后,我想以某种方式通知ViewModel
,对Model
的工作已经完成(例如,转换为灰度),我想显示该灰度图像在VM中。当我想做Model -> ViewModel
(ApplyKMM
在VM类中)但我想从ApplyKMM
移出ViewModel
时,它可以工作。那就是当我开始凝视星星时。
答案 0 :(得分:1)
基本上,将静态变量的更改通知给实例不是一个好习惯。
然后,让我们看一下您的代码:
Bitmaps
类未实现INotifyPropertyChanged
,因此,Filepath
发生更改时,不会通知任何内容(当然,它是静态属性)
在这种情况下,应使用局部变量来保存DisplayedImages
。然后DisplayedImage
上的更改应通过绑定进行更新。
BitmapImage _displayedImage;
public BitmapImage DisplayedImage
{
get { return displayedImage; }
set { displayedImage = value; NotifyPropertyChanged(nameof(DisplayedImage)); }
}
答案 1 :(得分:1)
它看起来像您想在静态属性更改时通知。为此,您可以使用StaticPropertyChanged
事件。
class ApplyKMM
{
#region Properties
static BitmapImage _Filepath;
public static BitmapImage Filepath
{
get { return _Filepath; }
set { if (_Filepath != value) { _Filepath = value; NotifyPropertyChanged(nameof(Filepath)); } }
}
#endregion
#region Static NotifyPropertyChanged
public static void NotifyStaticPropertyChanged(string propertyName)
{
StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
}
public void NotifyAllStaticPropertyChanged()
{
NotifyStaticPropertyChanged(string.Empty);
}
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
#endregion
}
请注意,这可以从WPF版本4.5中获得。
您可能还会发现this question有趣。