我有个问题。如何动态地将变量从视图模型绑定到视图?目前,它甚至没有显示。如果我不使用命令,它会很好地工作(当然,我只能绑定一次图像)。
我的
视图
:
namespace somestuff.View
{
public partial class WindowView : Window
{
public WindowView()
{
this.DataContext = new WindowViewModel();
InitializeComponent();
}
}
}
我的
视图,XAML
(缩短):
<Image Source="{Binding DisplayedImage}"/>
<Button Command="{Binding NewImageCommand}"/>
还有我的
ViewModel:
public WindowViewModel()
{
_canExecute = true;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string DisplayedImage //displaying image
{
get { return filepath; }
set { filepath = value; NotifyPropertyChanged(nameof(filepath)); }
}
public string filepath { get; set; } //var for binding
private bool _canExecute;
private ICommand _newImageCommand; //command for button
public ICommand NewImageCommand
{
get
{
return _newImageCommand ?? (_newImageCommand = new Commands.CommandHandler(() => GetImage(), _canExecute));
}
}
public void GetImage() { filepath = Pictures.GetNewImage(); } //command on button click
你能告诉我为什么触发命令后
GetImage()
在按钮上单击绑定到的图像
Image
没有改变?如果我移动
filepath = Pictures.GetNewImage();
从命令(更清楚地说,我不使用命令)所有的工作都很好,但我不能重新调用绑定到我的图像。您能告诉我,如何从视图模型动态地将属性绑定到视图中吗?当变量值(在本例中是filepath)更改时,我也希望更改视图控件。
谢谢你的建议。
编辑:
我有6个
图像
标签。我在里面像这样显示图像:
public BitmapImage DisplayedHighPerformanceImage
{
get { return kMMHP; }
set { kMMHP = value; NotifyPropertyChanged(nameof(kMMHP)); }
}
所以我需要
filepath
初始化6个不同的位图。然后我处理位图(例如,
kMMHP
)所以我想显示从
KMMHP
图像。
kMMHP = method1(); //displaying it
//other stuff do with diffrent bmps
kMMHP = method2(); //displaying it after second method with changed values