【发布时间】:2020-04-03 06:54:32
【问题描述】:
这个问题可能已经在 Stackoverflow 中提出,但我浏览了所有这些问题,但我的图像没有显示在窗口中,即使正确地选择了路径。我正在使用浏览器按钮导入图像。另外,我最近开始学习 MVVM 架构和 WPF 这是我的 Xaml 代码;
<!--Image block-->
<Label Grid.Row="5" Grid.Column="1" Style="{StaticResource LabelStyles}">Image :</Label>
<DockPanel Grid.Row="5" Grid.Column="2" VerticalAlignment="Center" MinHeight="30" LastChildFill="True">
<Button DockPanel.Dock="Left" Style="{StaticResource ButtonStyle}" Content="Browse" Margin="0,0,5,0" Command="{Binding Path=ImageCommand, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Name="FileBrowser" DockPanel.Dock="Right" Style="{StaticResource StyleControl}" HorizontalAlignment="Stretch" Padding="5" Text="{Binding Path= Patient.ImageView}"/>
</DockPanel>
<!--Image view block-->
<Image Name="ImageViewer" Grid.Row="6" Grid.Column="2" HorizontalAlignment="Left" MinWidth="95" MaxWidth="150" MinHeight="95" MaxHeight="150" Margin="0,0,0,10" Source ="{Binding Path= Patient.ImageView}"/>
我保留了一个单独的模型“PatientRecordDetailsModel”类来保留该属性。在那里我定义了 Image 属性如下
public class PatientRecordDetailsModel
{
private ImageSource m_imgSource;
public ImageSource ImageView {
get
{
return m_imgSource;
}
set
{
m_imgSource = value;
}
}
}
在视图模型类中,构造函数
class PatientRecordDetailsViewModel : INotifyPropertyChanged
{
public PatientRecordDetailsViewModel()
{
Patient = new PatientRecordDetailsModel();
}
// this is the Model property which takes the user inputs
public PatientRecordDetailsModel Patient
{
get { return m_patient; }
set
{
m_patient = value;
OnPropertyChange("Patient");
}
}
// The browser button command
public ICommand ImageCommand
{
get => new PatientRecordDetailsCommand(param => getImage(), param => canImage());
}
// the two methods
private bool canImage()
{
return true;
}
private void getImage()
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = @"C:\Users\Maneesha\Desktop\Dips Y-knots\images\";
dlg.Filter = "Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" +
"All files (*.*)|*.*";
if (dlg.ShowDialog() == true)
{
string m_fileName = dlg.FileName;
BitmapImage bitmap = new BitmapImage(new Uri(m_fileName));
Patient.ImageView = bitmap;
}
}
// INotify
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我不知道出了什么问题。我也尝试在 xaml 代码中添加 UpdateSourceTrigger。它没有用。我编辑了代码,我在 ViewModel 类中使用了 INotifyPropertyChanged。我保留一个单独的模型来保留属性。 请帮帮我!!!
【问题讨论】:
-
您需要触发一个
NotifyPropertyChanged事件,在该事件中为Patient属性设置图像。 -
嗨,我确实在视图模型中触发了 NotifyPropertyChanged,即使我没有包含它,现在我对其进行了编辑。它仍然没有工作。谢谢!
标签: c# wpf xaml mvvm data-binding