【发布时间】:2018-09-03 04:28:38
【问题描述】:
我正在尝试将我的 ViewModel (ComboBox) 中的 SelectedItems (ListView) 和 SelectedItem 或 SelectedCategory 多重绑定到只读的 TextBox。 OutputConverter 只是在为TextBox 创建文本之前检查是否至少选择了一项 (ListView) 和 TypeData (ComboBox)。
但是,如果我仅尝试使用 TextBox 仅在 ComboBox.SelectedItem 更改时更新,而不是在 ListView 内的 SelectedItems 更改时更新。
因此,我还从我的 ViewModel SelectedEntry (ListView)(与 SelectedItem 相同)中包含了 MultiBinding 的绑定。
现在我得到以下信息:
说明:
Selection 总是落后一步,并使用 ListView 中的前一个SelectedItems 绑定到TextBox.Text。即使我通过 CTRL 或 Shift + Click 选择多个条目。但是,如果 ComboBox.SelectedItem 发生更改,它会按预期更新 TextBox。
如果 ListView 中的 Selection 发生更改,我如何获得行为,TextBox 会立即相应地更新其内容(最好我想使用我的 ViewModel 的 SelectedEntries 而不是 ListView 的 SelectedItems,如果可能以符合 MVVM 的方式)?
编辑:
- 我注意到当转换器被称为 SelectedEntry(实现 INotifyPropertyChanged) 已更新,但 SelectedEntries (ObservableCollection 和实现 INotifyPropertyChanged)不是。
- 我还包含了一个调用命令的 SelectionChanged 事件 并将 SelectedItems 作为参数传递给命令。如果说 可能会有所帮助,但我宁愿有一个适当的绑定 相应更新。
代码:
模型类型数据(组合框):
public class TypeData : INotifyPropertyChanged
{
public enum Type
{
NotSet = '0',
A = 'A',
B = 'B',
C = 'C'
}
private string name;
public string Name
{
get { return name; }
set
{
name = value;
//OnPropertyChanged("Name");
OnPropertyChanged(nameof(Name));
}
}
private Type category;
public Type Category
{
get { return category; }
set { category = value; }
}
public TypeData(string name)
{
Name = name;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public override string ToString()
{
return Name;
}
}
模型条目(ListView):
public class Entry : INotifyPropertyChanged
{
private string title;
public string Title
{
get { return title; }
set
{
title = value;
OnPropertyChanged(nameof(Title));
}
}
private string author;
public string Author
{
get { return author; }
set
{
author = value;
OnPropertyChanged(nameof(Author));
}
}
private string year;
public string Year
{
get { return year; }
set
{
year = value;
OnPropertyChanged(nameof(Year));
}
}
public Entry(string title, string author, string year)
{
Title = title;
Author = author;
Year = year;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
视图模型:
public class MainViewModel
{
public ObservableCollection<Entry> Entries { get; set; }
public Entry SelectedEntry { get; set; }
public ObservableCollection<Entry> SelectedEntries { get; set; }
public ObservableCollection<TypeData> Types { get; set; }
private TypeData selectedCategory;
public TypeData SelectedCategory { get; set; }
public RelayCommand<object> SelectionChangedCommand { get; set; }
public MainViewModel()
{
Entries = new ObservableCollection<Entry>
{
new Entry("Title1", "Author1", "Year1"),
new Entry("Title2", "Author2", "Year2"),
new Entry("Title3", "Author3", "Year3"),
new Entry("Title4", "Author4", "Year4"),
};
Types = new ObservableCollection<TypeData>
{
new TypeData("A"),
new TypeData("B"),
new TypeData("C"),
};
SelectionChangedCommand = new RelayCommand<object>(items =>
{
var selectedEntries = (items as ObservableCollection<object>).Cast<Entry>();
SelectedEntries = new ObservableCollection<Entry>(selectedEntries);
});
}
}
XAML:
<Window x:Class="MvvmMultiBinding.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MvvmMultiBinding"
xmlns:m="clr-namespace:MvvmMultiBinding.Model"
xmlns:vm="clr-namespace:MvvmMultiBinding.ViewModel"
xmlns:conv="clr-namespace:MvvmMultiBinding.View.Converter"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<vm:MainViewModel></vm:MainViewModel>
</Window.DataContext>
<Window.Resources>
<conv:OutputConverter x:Key="OutputConverter"/>
</Window.Resources>
<Grid>
<DockPanel>
<ListView Name="ListViewEntries" ItemsSource="{Binding Entries}" SelectedItem="{Binding SelectedEntry}" DockPanel.Dock="Top">
<ListView.View>
<GridView>
<GridViewColumn Header="Title" Width="250" DisplayMemberBinding="{Binding Title}" />
<GridViewColumn Header="Author" Width="150" DisplayMemberBinding="{Binding Author}" />
<GridViewColumn Header="Year" Width="50" DisplayMemberBinding="{Binding Year}" />
</GridView>
</ListView.View>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding DataContext.SelectionChangedCommand, ElementName=ListViewEntries}"
CommandParameter="{Binding SelectedItems, ElementName=ListViewEntries}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListView>
<ComboBox ItemsSource="{Binding Types}" SelectedItem="{Binding SelectedCategory}" MinWidth="200" DockPanel.Dock="Right"/>
<TextBox IsReadOnly="True" DockPanel.Dock="Left">
<TextBox.Text>
<MultiBinding Converter="{StaticResource OutputConverter}">
<Binding ElementName="ListViewEntries" Path="SelectedItems" Mode="OneWay"/>
<!--<Binding Path="SelectedEntries" Mode="OneWay"/>-->
<Binding Path="SelectedCategory" Mode="OneWay"/>
<!-- Without it converter is not called after selection changes -->
<Binding Path="SelectedEntry" Mode="OneWay"/>
</MultiBinding>
</TextBox.Text>
</TextBox>
</DockPanel>
</Grid>
输出转换器:
public class OutputConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
System.Collections.IList items = (System.Collections.IList)values[0];
var entries = items.Cast<Entry>();
TypeData type = values[1] as TypeData;
List<Entry> selectedEntries = new List<Entry>();
foreach (var entry in entries)
{
selectedEntries.Add(entry);
}
StringBuilder sb = new StringBuilder();
// ComboBox and Selection must not be empty
if (type != null && selectedEntries.Count > 0)
{
foreach (var selectedEntry in selectedEntries)
{
sb.AppendFormat("{0} {1}\n\n", selectedEntry.Author, type);
}
}
return sb.ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
【问题讨论】:
-
MainViewModel 应该实现 INotifyPropertChanged 以便 SelectedEntry 等将引发正确的事件
-
我看好像更干净了。但是我将如何为 IEnumerable 项目实现 INotifyPropertyChanged,例如ViewModel 中的 SelectedEntries(也是 ObserverableCollection)?
-
我会在 Entry 类上添加一个名为 IsSelected 的属性并将其绑定到条目的视图(Checkbox.IsChecked 或类似),然后 SelectedEntries 变得多余或简单的 Linq 表达式.....哪里(e=>e.IsSelected)
标签: c# wpf listview mvvm multibinding