我有一個ListView
我綁定到ObservableCollection
與泛型MyCommand
。當我更改MyCommand
對象中的屬性時,ListView
未更新。ListView綁定INotifyPropertyChanged工作不正常
轉換器:
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>
查看代碼隱藏:
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
列表,它會更新視圖。
在MyCommand的構造函數中實際編譯了'CommandBindings = bindings;'嗎?除此之外,您還應該向我們展示ListView的ItemTemplate。 – Clemens
你在ListView中使用了什麼ItemTemplate? – SuperOli
ups只是寫在這裏..我會更正它 – NtFreX