C# MVVM中松散绑定类的数据绑定
我是MVVM新手,有这样的情况:假设我有两个松散耦合的类:C# MVVM中松散绑定类的数据绑定,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我是MVVM新手,有这样的情况:假设我有两个松散耦合的类: public class Client { public string Id {get; set;} public string Name {get; set;} public string Adress {get; set;} public string AccountId {get; set;} } public class Account { public string Id {get; set;} public string
public class Client
{
public string Id {get; set;}
public string Name {get; set;}
public string Adress {get; set;}
public string AccountId {get; set;}
}
public class Account
{
public string Id {get; set;}
public string BankName {get; set}
public string AccountDescription {get; set;}
}
其中Client.AccountId==Account.Id
在my.xaml.cs中,我有:
public partial class BankingView : UserControl, INotifyPropertyChanged
{
private ObservableCollection<Client> Clients {get; set;}
private GlobalAccounts Acounts {get; set;}
//geting data methods and other stuff
}
问题:应该如何从my.xaml.cs/.xaml添加和调用这种类型的ViewModel,以及绑定应该是什么样子?问题是,在这种情况下,视图模型类不应该被称为“松散耦合”。它们应该为视图建模,因此得名
因此,如果要显示客户机
帐户的银行名
,则应创建客户机
的视图模型,该视图模型具有要绑定的银行名
或帐户
属性
换言之;如果当前正在绑定到某个域对象,则应创建另一个类来包装该对象的属性,并添加视图需要绑定到的任何属性。毕竟,这就是视图模型的用途
助手类或列表框的视图模型负责实例化这些“子”视图模型对象。不清楚您想要实现什么。BankingView是否应该从所有客户的集合中选择一个客户?为什么它需要了解帐户?视图模型应该知道客户和帐户之间的关系。BankingView假设显示所有客户,并根据该客户的AccountId选择相应的帐户,并相应地显示帐户信息。这听起来很奇怪。它应该只选择一个客户端,并且应该由视图模型选择相应的帐户。控件(或其他控件)可以显示所选帐户。不同的数据存储在不同的API中。客户机和帐户只是相关的,因为它们有关系:Client.AccountId==Account.Id。没错,这是一个应该由视图模型管理的关系。
public class GlobalAccounts : INotifyPropertyChanged
{
private ObservableCollection<Acount> Acounts {get; set;}
//methods to update Acounts
}
<ListBox ItemsSource="{Binding Clients, ElementName=uc}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Name:" TextAlignment="Right"/>
<TextBlock Grid.Column="1" Text="{Binding Name}"/>
<TextBlock Grid.Row="1" Text="Adress:" TextAlignment="Right"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Adress}"/>
<TextBlock Grid.Row="2" Text="BankName:" TextAlignment="Right"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text={Binding ?????? BankName} Tooltip={Binding ?????? AccountDescription} />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public class ClientAccountsViewModel: INotifyPropertyChanged
{
public string AccountId {get; set;} //Account Id that needs to be matched
public GlobalAccounts Accounts {get; set;} //singletone of all the Accounts
public Acount CorrespondingAccount {get; set;} //account coresponding to client
//logic that would find the Corresponding account based on SelectedClient set/changed
}