我有ListView
我绑定到ObservableCollection
,其泛型类型为MyCommand
。当我更改MyCommand
对象中的属性时,ListView
不会更新。
转换器:
public class CommandToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
查看:
<ListView ItemsSource="{Binding Commands}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource CommandToStringConverter}}"></TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
查看CodeBehind:
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
视图模型:
using Prism.Mvvm;
public class MainViewModel : BindableBase
{
private ObservableCollection<MyCommand> _commands;
public ObservableCollection<MyCommand> Commands
{
get { return _commands; }
set { SetProperty(ref _commands, value); }
}
public MainViewModel()
{
//setup test data
Commands = new ObservableCollection<MyCommand>(new [] {
new MyCommand(
CommandType.HotKey,
new [] {
new MyCommandBinding(HotKey.F5),
new MyCommandBinding(HotKey.F1)
})
});
}
}
型号:
public enum CommandType
{
HotKey
}
public enum HotKey
{
F1,
F5,
A,
B,
C
}
public class MyCommand : BindableBase
{
private CommandType _commandType;
public CommandType CommandType
{
get { return _commandType; }
set { SetProperty(ref _commandType, value); }
}
private ObservableCollection<MyCommandBinding> _commandBindings;
public ObservableCollection<MyCommandBinding> CommandBindings
{
get { return _commandBindings; }
set { SetProperty(ref _commandBindings, value); }
}
public MyCommand(CommandType commandType, IEnumerable<MyCommandBinding> bindings)
{
CommandType = commandType;
CommandBindings = new ObservableCollection<MyCommandBinding>(bindings);
}
public override string ToString()
{
var text = string.Empty;
foreach(var binding in CommandBindings)
{
if(!string.IsNullOrEmpty(text)) text += " + ";
text += binding.HotKey.ToString();
}
return CommandType.ToString() + ", " + text;
}
}
public class MyCommandBinding : BindableBase
{
private HotKey _hotKey;
public HotKey HotKey
{
get { return _hotKey; }
set { SetProperty(ref _hotKey, value); }
}
public MyCommandBinding(HotKey hotKey)
{
HotKey = hotKey;
}
}
现在,当我更改属性Commands[0].CommandBindings[0].HotKey = HotKey.A;
时,视图不会更新。
我错过了什么或做错了什么?
修改
我现在正在使用ItemTemplate
和转换器,我仍然有相同的行为(初始帖子已更新)。如果我在转换器中调用ToString
方法或者使用属性,我没有任何区别。就像Brian Lagunas指出的那样,如果我重新分配Commands
列表,它会更新视图。
答案 0 :(得分:2)
您似乎正在使用对象的ToString来表示ListView中对象的显示。在属性更改时不会重新查询ToString。