Edw*_*uay 10 wpf selecteditem mvvm
在下面的代码中,当用户在组合框中选择Customer时,客户的名称将显示在文本框中.我在ViewModel上填充了一个带有ObservableCollection属性的Combox框,但是如何在ViewModel中处理SelectedItem事件?
使用代码隐藏实现这一点很容易,如下所示,但是如何使用MVVM模式执行此操作?
我目前在我可以使用的基本MVVM模板中有DelegateCommand和AttachedBehaviors,但是当"combobox选择一个新项目"时,我无法弄清楚如何让它们触发.
视图:
<Window.Resources>
<DataTemplate x:Key="CustomerTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding LastName}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<DockPanel LastChildFill="False" Margin="10">
<ComboBox
x:Name="CustomerList"
ItemTemplate="{StaticResource CustomerTemplate}"
HorizontalAlignment="Left"
DockPanel.Dock="Top"
Width="200"
SelectionChanged="CustomerSelected"
ItemsSource="{Binding Customers}"/>
<TextBlock x:Name="CurrentlySelectedCustomer"/>
</DockPanel>
Run Code Online (Sandbox Code Playgroud)
代码背后:
private void CustomerSelected(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
Customer customer = (Customer)CustomerList.SelectedItem;
CurrentlySelectedCustomer.Text = String.Format("{0} {1}", customer.FirstName, customer.LastName);
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ris 12
您应该能够将ViewModel中的属性绑定到组合框的SelectedItem属性.如果将其设置为双向绑定,则会在SelectedItem更改时收到通知,因为它将触发属性上的set方法.
视图模型:
public ObservableCollection Customers
{
get { return _customers; }
set
{
if (_customers != value)
{
_customers = value;
OnPropertyChanged("Customers");
}
}
}
public Customer SelectedCustomer
{
get { return _selectedCustomer; }
set
{
if (_selectedCustomer != value)
{
_selectedCustomer= value;
LastName= value.LastName;
OnPropertyChanged("SelectedCustomer");
}
}
}
public Customer LastName
{
get { return _lastName; }
set
{
if (_lastName!= value)
{
_lastName= value;
OnPropertyChanged("LastName");
}
}
}
Run Code Online (Sandbox Code Playgroud)
XAML:
<DockPanel LastChildFill="False" Margin="10">
<ComboBox
x:Name="CustomerList"
ItemTemplate="{StaticResource CustomerTemplate}"
HorizontalAlignment="Left"
DockPanel.Dock="Top"
Width="200"
SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
ItemsSource="{Binding Customers}"/>
<TextBlock x:Name="CurrentlySelectedCustomer"
Text="{Binding LastName}"/>
</DockPanel>
Run Code Online (Sandbox Code Playgroud)
rud*_*ler 10
请访问www.codeproject.com 查看此应用程序.在这里,我使用CollectionView来检测当前选定的项目
更新
使用CollectionView检测当前所选项目
ListCollectionView view = (ListCollectionView)CollectionViewSource.GetDefaultView(Customers);
view.CurrentChanged += delegate
{
SelectedCustomer= (Customer)view.CurrentItem;
};
Run Code Online (Sandbox Code Playgroud)
记得还要设置IsSynchronizedWithCurrentItem ="True"
| 归档时间: |
|
| 查看次数: |
17402 次 |
| 最近记录: |