C# MVVM如何将ListBox SelectedItem放入ViewModel类的实例中
我的列表框的SelectedItem有问题。我想将所选项目置于我的HealthDiseaseViewModel的突出显示属性中 这是我的ViewModel:C# MVVM如何将ListBox SelectedItem放入ViewModel类的实例中,c#,wpf,xaml,mvvm,listbox,C#,Wpf,Xaml,Mvvm,Listbox,我的列表框的SelectedItem有问题。我想将所选项目置于我的HealthDiseaseViewModel的突出显示属性中 这是我的ViewModel: public class HealthDiseaseViewModel : ObservableCollection<HealthDisease> { private string _feedBack; HealthDiseaseDb _db = new HealthDiseaseDb(); publ
public class HealthDiseaseViewModel : ObservableCollection<HealthDisease>
{
private string _feedBack;
HealthDiseaseDb _db = new HealthDiseaseDb();
public HealthDiseaseRetrieveSingleCommand RetrieveSingleCommand { get; set; }
public HealthDiseaseRetrieveManyCommand RetrieveManyCommand { get; set; }
public HealthDiseaseUpdateCommand UpdateCommand { get; set; }
public HealthDisease Entity { get; set; }
public HealthDisease Highlighted { get; set; }
public List<HealthDisease> EntityList { get; set; }
public HealthDiseaseViewModel()
{
RetrieveSingleCommand = new HealthDiseaseRetrieveSingleCommand(this);
RetrieveManyCommand = new HealthDiseaseRetrieveManyCommand(this);
UpdateCommand = new HealthDiseaseUpdateCommand(this);
Highlighted = new HealthDisease();
Entity = new HealthDisease();
RetrieveMany(Entity);
}
#region Methods
public void Retrieve(HealthDisease parameters)
{
Highlighted = _db.Retrieve(parameters);
}
public void RetrieveMany(HealthDisease parameters)
{
EntityList = new List<HealthDisease>();
EntityList = _db.RetrieveMany(parameters);
IList<HealthDisease> toBeRemoved = Items.ToList();
foreach (var item in toBeRemoved)
{
Remove(item);
}
foreach (var item in EntityList)
{
Add(item);
}
}
public void Insert(HealthDisease entity)
{
bool doesExist = false;
if (_db.Insert(entity, SessionHelper.CurrentUser.Id, ref doesExist))
{
_feedBack = "Item Successfully Saved!";
RetrieveMany(new HealthDisease());
}
else if (doesExist)
{
_feedBack = "Item Already Exists!";
}
else
{
_feedBack = "Not All Fields Were Filled-In!";
}
MessageBox.Show(_feedBack, "Item Insertion");
}
public void Update(HealthDisease entity)
{
bool doesExist = false;
if (_db.Update(entity, SessionHelper.CurrentUser.Id, ref doesExist))
{
_feedBack = "Item Successfully Updated!";
RetrieveMany(new HealthDisease());
}
else if (doesExist)
{
_feedBack = "Item Already Exists!";
}
else
{
_feedBack = "Not All Fields Were Filled-In!";
}
MessageBox.Show(_feedBack, "Item Edition");
}
public void Delete(HealthDisease entity)
{
var answer = MessageBox.Show(String.Format("Are you sure you want to delete \n{0}?", entity.Name),
"Item Deletion", MessageBoxButtons.YesNo);
if (answer == DialogResult.No)
{
return;
}
if (_db.Delete(entity, SessionHelper.CurrentUser.Id))
{
_feedBack = "Item Successfully Deleted!";
RetrieveMany(new HealthDisease());
}
MessageBox.Show(_feedBack, "Item Deletion");
}
#endregion
}
公共类HealthDiseaseViewModel:ObservableCollection
{
私有字符串反馈;
HealthDiseaseDb_db=新的HealthDiseaseDb();
公共卫生疾病检索SingleCommand检索SingleCommand{get;set;}
public HealthDiseaseRetrieveManyCommand RetrieveManyCommand{get;set;}
public HealthDiseaseUpdateCommand和UpdateCommand{get;set;}
公共健康疾病实体{get;set;}
公共卫生{get;set;}
公共列表EntityList{get;set;}
公共卫生疾病视图模型()
{
RetrieveSingleCommand=新健康疾病RetrieveSingleCommand(本);
RetrieveManyCommand=新健康疾病RetrieveManyCommand(本);
UpdateCommand=新的HealthDiseaseUpdateCommand(此);
突出显示=新的健康疾病();
实体=新的健康疾病();
检索多(实体);
}
#区域方法
公共无效检索(HealthDisease参数)
{
突出显示=_db.Retrieve(参数);
}
public void RetrieveMany(HealthDisease参数)
{
EntityList=新列表();
EntityList=_db.RetrieveMany(参数);
IList toBeRemoved=Items.ToList();
foreach(待删除的var项目)
{
删除(项目);
}
foreach(EntityList中的变量项)
{
增加(项目);
}
}
公共无效插入(健康疾病实体)
{
布尔-多尔性别歧视=错误;
if(_db.Insert(entity,SessionHelper.CurrentUser.Id,ref doesExist))
{
_反馈=“项目已成功保存!”;
RetrieveMany(新健康疾病());
}
否则如果(性别歧视)
{
_反馈=“项目已存在!”;
}
其他的
{
_反馈=“并非所有字段都已填写!”;
}
MessageBox.Show(_反馈,“项目插入”);
}
公共无效更新(健康疾病实体)
{
布尔-多尔性别歧视=错误;
if(_db.Update(entity,SessionHelper.CurrentUser.Id,ref doesExist))
{
_feedBack=“项目已成功更新!”;
RetrieveMany(新健康疾病());
}
否则如果(性别歧视)
{
_反馈=“项目已存在!”;
}
其他的
{
_反馈=“并非所有字段都已填写!”;
}
MessageBox.Show(_反馈,“项目版本”);
}
公共作废删除(健康疾病实体)
{
var answer=MessageBox.Show(String.Format(“是否确实要删除\n{0}?”,entity.Name),
“项目删除”,MessageBoxButtons.YesNo);
如果(答案==DialogResult.No)
{
返回;
}
if(_db.Delete(entity,SessionHelper.CurrentUser.Id))
{
_feedBack=“项目已成功删除!”;
RetrieveMany(新健康疾病());
}
MessageBox.Show(_反馈,“项目删除”);
}
#端区
}
我将我的列表框的SelectedItem绑定到Highlighted,我希望将Highlighted.Name和Highlighted.Description绑定到TextBlocks,但TextBlocks不显示SelectedItem。我可以使用SelectedItem.Name和SelectedItem.Description在这里进行操作,但问题是,即使我还没有按下保存按钮,它也会自动更新列表框。使用突出显示的对象可以解决这个问题,但我现在已经花了好几个小时的时间感到沮丧。
这是我的标记。我从ViewModel中省略了绑定到UpdateCommand的SaveButton
<Grid Name="MainGrid" Background="Aqua" MinWidth="500" MinHeight="400"
DataContext="{Binding Source={StaticResource HealthViewModel}}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=Highlighted.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
<ListBox x:Name="EntityListBox" Margin="10,0" Height="380"
ItemsSource="{Binding }"
DisplayMemberPath="Name"
SelectedItem="{Binding Path=Highlighted, Mode=TwoWay,
Converter={StaticResource ToHealthDiseaseConverter},
UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</Grid>
我可以为您提供一个快速的答案,但希望您不要停在这里,试图找出绑定到对象属性中不起作用的原因。DependencyProperty绑定到使用正确的raise PropertyChanged触发器实现INotifyPropertyChanged的实例。它不绑定到实例的“值”。看看你是否能找出为什么绑定到高亮显示的.Name无法工作 我为您创建了一个简化的示例
<Window x:Class="WpfTestProj.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfTestProj"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=local:MainViewModel, IsDesignTimeCreatable=False}"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<StackPanel Orientation="Vertical">
<StackPanel>
<TextBlock Text="{Binding Path=HighlightedName}" />
</StackPanel>
<StackPanel>
<ListBox x:Name="EntityListBox" Margin="10,0"
ItemsSource="{Binding EntityList}"
DisplayMemberPath="Name"
SelectedItem="{Binding Path=Highlighted, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</StackPanel>
</Grid>
公共抽象类ViewModelBase:INotifyPropertyChanged
{
公共事件属性更改事件处理程序属性更改;
[NotifyPropertyChangedInvocator]
受保护的虚拟void OnPropertyChanged([CallerMemberName]字符串propertyName=null)
{
var handler=PropertyChanged;
if(handler!=null)handler(这是新的PropertyChangedEventArgs(propertyName));
}
}
公共卫生类疾病
{
公共字符串名称{get;set;}
}
公共类MainViewModel:ViewModelBase
{
公共ObservableCollection EntityList{get;set;}
公共主视图模型()
{
RetrieveMany();
}
私有void RetrieveMany()
{
EntityList=新的ObservableCollection
{
新的健康疾病{Name=“疾病A”},
新的健康疾病{Name=“疾病B”},
新的健康疾病{Name=“疾病C”}
};
}
强调私人健康;
公共卫生及疾病
{
获取{return highlighted;}
设置
{
突出显示=值;
OnPropertyChanged();
OnPropertyChanged(“HighlightedName”);
}
}
公共字符串高亮显示名称
{
get{return Highlighted==null?string.Empty:Highlighted.Name;}
}
}
我可以为您提供一个快速的答案,但希望您不要停在这里,试图找出绑定到对象属性中不起作用的原因。DependencyProperty绑定到实现INotifyPropertyChanged并使用适当的raise PropertyCha的实例
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class HealthDisease
{
public string Name { get; set; }
}
public class MainViewModel : ViewModelBase
{
public ObservableCollection<HealthDisease> EntityList { get; set; }
public MainViewModel()
{
RetrieveMany();
}
private void RetrieveMany()
{
EntityList = new ObservableCollection<HealthDisease>
{
new HealthDisease {Name = "Disease A"},
new HealthDisease {Name = "Disease B"},
new HealthDisease {Name = "Disease C"}
};
}
private HealthDisease highlighted;
public HealthDisease Highlighted
{
get { return highlighted; }
set
{
highlighted = value;
OnPropertyChanged();
OnPropertyChanged("HighlightedName");
}
}
public string HighlightedName
{
get { return Highlighted == null ? string.Empty : Highlighted.Name; }
}
}