【发布时间】:2017-02-24 10:50:24
【问题描述】:
我有一个简单的 MVVM WPF 应用程序,它带有数据库优先的 EF dbContext(在我的应用程序中是 Global.Database),它在我的应用程序中长期存在。
我有一个带有ItemsSource 的列表框的窗口,该列表框绑定到名为Clients 的viewmodel 属性,这是我的dbmodel Client 的ObservableCollection。
此列表框的SelectedItem 绑定到名为SelectedClient 的视图模型属性。
在Client 实体类中有一个名为last_status 的字段,它是我数据库中的一个简单整数。
所以,在我看来,当我从列表框中选择客户端时,绑定到 SelectedClient 的last_status 的标签应该显示last_status 的值。
我在视图模型中添加了一个按钮和一个刷新命令。我想要的是:当我在我的数据库中为客户端手动更改last_status 并在我的视图中按刷新按钮时,标签的内容应该会改变。但我完全不知道如何实现这一目标。这是我的视图模型代码的一部分(我使用 Catel,但对于这种情况并不重要):
public ClientManagerWindowViewModel()
{
RefreshClientInfoCommand = new Command(OnRefreshClientInfoCommandExecute);
Clients = new ObservableCollection<Client>();
RefreshClients();
}
public ObservableCollection<Client> Clients
{
get { return GetValue<ObservableCollection<Client>>(ClientsProperty); }
set { SetValue(ClientsProperty, value); }
}
public static readonly PropertyData ClientsProperty = RegisterProperty("Clients", typeof(ObservableCollection<Client>));
public Client SelectedClient
{
get
{return GetValue<Client>(SelectedClientProperty);}
set
{
SetValue(SelectedClientProperty, value);
}
}
public static readonly PropertyData SelectedClientProperty = RegisterProperty("SelectedClient", typeof(Client));
//here is my refresh button command handler:
public Command RefreshClientInfoCommand { get; private set; }
private void OnRefreshClientInfoCommandExecute()
{
RefreshClientInfo(SelectedClient);
}
//and here is my "logic" for working with dbcontext:
private void RefreshClients()
{
var qry = (from c in Global.Database.Clients where c.client_id != 1 select c).ToList();
Clients = new ObservableCollection<Client>(qry);
}
private void RefreshClientInfo(Client client)
{
Global.Database.Entry(client).Reload();
}
我的列表框 XAML:
<ListBox
x:Name="ClientsListBox"
Grid.Row="1"
Margin="5"
DisplayMemberPath="fullDomainName"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Clients}"
SelectedItem="{Binding SelectedClient}" />
我的标签的 XAML:
<Label Margin="5" Content="{Binding SelectedClient.last_status}" />
对于一个按钮:
<Button Command="{Binding RefreshClientInfoCommand}" Content="↻"/>
现在,当我在数据库中手动更改客户的 last_status 值并按下刷新按钮时,什么也没有发生。但是当我在列表框中选择另一个客户端然后返回到所需的客户端时 - 标签内容正确更新。我知道,也许我错过了一些非常愚蠢和简单的事情,但我无法弄清楚到底是什么。也许我需要在我的按钮命令处理程序中强制更改SelectedClient,或者以某种方式调用SelectedClients setter...
请帮我。非常感谢。
【问题讨论】:
-
你也应该刷新绑定。
标签: c# wpf entity-framework mvvm catel